Go to the menu - Go to the contents

Filling out forms with PHP


Tutorial's information

Avatar
Author : M@teo21
Nb of visits : 1 140


More information More information
One of the most interesting applications of PHP is the ability to work on forms to fill out, in a very powerful way.

The only way your guests can enter information on your site is by filling out a form, in other words to produce interactivity.
On a forum for instance, you have to enter some text before clicking on a button to send your message. It's the same for a guest book or a mini-chat. Forms are needed everywhere.

You'll find out that there are some HTML reminders in this chapter... And this is not a coincidence: in this case, PHP and HTML are closely related.
What do we need PHP for? It will allow us to process the data entered by the user. This will be the base for all our future practical work (guest book, news etc.), so you might want to pay attention.

Let's go! :D
Previous Chapter Contents Next Chapter

How to use a form

In HTML, to indicate that we're going to insert a form, the tag <form> is used like this:

Code: HTML
1
2
3
4
5
6
7
8
<form method="post" action="target.php">
 
<p>
    We will put our form's elements here.<br />
    Note that there is no PHP for the moment.
</p>
 
</form>


What you have to recall is that our form's content is put between the tags <form> and </form>
There are two interesting attributes to know about the tag <form>:

  • method="post": you have to know that there are different ways to send the form (different "methods"). Just remember the "post" method, which is the only one we will be interested in for PHP. It means you will always put method="post" for your forms!
  • action="target.php": essential. It is the name of the page that will be called when the user will have sent the form (i.e when the "send" button will be clicked! ^^ ) For instance, the previous code is located on the page form.php. Once the form has been sent, it loads the page target.php in which we will process the guest's data.



Don't forget that you're supposed to work on 2 different pages: the one containing the form (form.php in our example), and the one receiving the form's data to process them (target.php).

But now you may wonder if and why we actually used one page only for the practical work "password" and "minichat". Yes, we did, the target page was also the one of the form. We had put not only the form in minichat.php, but also the data processing (because we had an action="minichat".php" that sent back to the same page).

Eventually, things might become clearer for you:

  • The first time that the minichat is loaded, we check if some variables sent by the form like $_POST['nickname'] exist (that's what isset is here for). We know that we must not write any information in the database (we skip the if), because the first time we loaded the page we did not enter anything in the form.
  • This time when a message has been entered, the page reloads with information from the form entered by the user (like the nickname). As a result, $_POST['nickname'] exists, SO we know we must save something.


And all this is done on the very same page :D

In practice, you will come to see that the preference goes to two distinct pages because it's easier to manage (it spares us the use of isset). But quite often you will be compelled to work on the same page, and consequently to use the same technique as the previous practical work's.


In the variables' chapter, I quickly evoked forms including text-area fields and you may remember that I had promised you we'd get back to them later to see all the form's elements we can process with PHP.
The time has come :)

The form's elements

You may know it already but in a form, you can put a lot of different elements: text fields, buttons, check boxes etc.
I will list them all, and show you how to use each and every one of them. I bet with this you'll be prepared to brave the forms by yourselves :pirate:

Small text fields



This is what a text field looks like:
User image

In HTML, it is inserted simply with the tag:
<input type="text" />

For passwords, you can use type="password", which will hide the text entered by the guest.


But you will have to add two attributes, which will be very useful:

  • name: text field's name. Choose it accurately because it is going to produce a variable. For instance:
    <input type="text" name="nickname" />
    In target.php, it will create a variable $_POST['nickname']
  • value: what the text field contains at the beginning. The default text field is empty. But it can be really convenient to pre-fill the field: on the minichat practical work, for instance, it would be easy to write the user's nickname automatically! Example:
    <input type="text" name="nickname" value="M@teo21" />


I know you're starting to worry because you haven't seen any PHP yet, and you're afraid of the terrible thing you might fall into.
Calm down, there's nothing coming :p

It's quite simple actually: the text that the guest will have entered will be available in target.php through a variable called $_POST['nickname'].

And this is nothing new since we have already seen it in the variables chapter. By the way, I figured that I would just give you the example I had already made instead of creating a new one (what do you mean, lazybones? :whistle: )

Code: HTML
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<p>
    This page contains HTML only as well.<br />
    Please enter your first name:
</p>

<form action="target.php" method="post">
<p>
<input type="text" name="first_name" /> <input type="submit" value="Validate" />
</p>
</form>



Code: PHP
1
2
3
4
5
<p>Hello!</p>

<p>I know your name, ha-ha! Your name is <?php echo $_POST['first_name']; ?> !</p>

<p>If you want to change your first name, <a href="3.3.1.php">click here</a> to go back to call.php</p>



This button will open the page call.php:



In target.php, a variable $_POST['first_name'] containing what the user has entered in the form has been displayed.

I hadn't talked about htmlspecialchars (to avoid HTML being dangerous) so far because we were still in the tutorial's first chapters. But to ensure the security, you MUST apply a htmlspecialchars to the variable $_POST['first_name']. If you test my example, you'll see that I took the precaution of applying a htmlspecialchars! :D
The use of the function mysql_real_escape_string is not required here. You only need it when you have to carry out an SQL query with this variable, which is not the case here.


To go back to the Mini-Chat, the nickname can be written again in the field "nickname" without any problem if the variable $_POST['nickname'] exists. It would give us something like:

Code: PHP
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<input type="text" name="nickname"
<?php
if (isset($_POST['nickname'])) // If we have the nickname entered by the guest
{
    echo 'value="' . $_POST['nickname'] . '"'; // We pre-fill the field with the guest's nickname
}

// Without forgetting to close the tag <input /> at the bottom:
?>

/>


Roughly speaking, we have put some PHP right in the middle of the tag <input /> (we sure can).
If we have the guest's nickname, we'll then add the attribute value="nickname", which will pre-fill the text field. :)

Please don't forget to put the /> at the very end to close the tag <input />


Among other things, you'll acknowledge the significance of concatenation and apostrophes to separate the text from variables. It has spared us the use of backslash before the inverted commas.



Big text fields



The big text field (also called "multiline input field"), looks like that:
User image

We can write as many lines as we want. It is more appropriate if the guest has to write a long message for instance.

We will use the following HTML code to insert this big text field.

Code: HTML
1
2
3
<textarea name="message" rows="8" cols="45">
Your message here.
</textarea>


Here again, we have the attribute name that will define the name of the variable to be created in target.php. In our case, it will be the variable $_POST['message'].
More specific thing: there's no value attribute. Actually, here the default text is written between <textarea> and </textarea>. Much more convenient to make an echo in between ^^
If you don't want to put any default value, just don't write anything between <textarea> and </textarea>

Drop down box



Here it comes:
User image

We use the following HTML code:
Code: HTML
1
2
3
4
5
6
<select name="choice">
    <option value="choice1">Choice1</option>
    <option value="choice2">Choice2</option>
    <option value="choice3">Choice3</option>
    <option value="choice4">Choice4</option>
</select>


We just have to use the tag <select>, to which we give a name (here "choice").
Afterwards, we write the different options... before closing the tag with </select>.

There will be a variable $_POST['choice'] created, which will contain the choice made by the user. If he has chosen "Choice 3", the variable $_POST['choice'] will equal the correspondent value, i.e "choice3".

Defining the default choice is an important thing, and it could be useful to know how to do it. It should be the first one, but if you add the attribute selected="selected" to a tag <option>, it will then become the default choice. We could write:
<option value="choice3" selected="selected">Choice 3</option>

Check Boxes



It looks like that:

User image


This is the code we're going to use to display check boxes:

Code: HTML
1
<input type="checkbox" name="box" /> My checkbox


Here again, we name the check box ("box"). This name is going to generate a variable in the target page, for instance $_POST['box'].

  • If the box is checked, the value of $_POST['box'] will be "on".
  • If it's not ckecked, $_POST['box'] will not contain anything (NULL).



If you want the box to be checked by default, you'll need to add the attribute checked="checked". As for:
<input type="checkbox" name="box" checked="checked" />
The box will be checked already.

Radio Buttons



They work by groups of 2 minimum. For instance:

User image

The code accounting for this example is:

Code: HTML
1
2
3
Do you like hamburgers?
<input type="radio" name="hamburgers" value="yes" checked="checked" /> yes
<input type="radio" name="hamburgers" value="no" /> No


As you can see, the two radio buttons have the same name ("hamburgers"). It is essential because they work by "groups": all radio buttons from a same group are called the same.
It allows the browser to know which radio buttons to disable when another one from the group is activated. Indeed, being able to check "Yes" and "No" at the same time would be stupid :D

To pre-check one of these radio buttons, just do the same as for check boxes: add a checked. As you can see here, "Yes" is checked by default.

A variable $_POST['hamburgers'] will be created in the target page. It will have the value of the radio button chosen by the guest. If we like hamburgers, we'll then have $_POST['hamburgers'] = 'yes'.
Don't forget to fill the radio button "value" attribute because it will define the variable's value :)

Hidden fields



What does this handy thing consist in? It is a code in your form that will not be visible to the eyes of your guest, but it will create a variable with a value.
Suppose you want to remember that the guest's nickname is "Mateo21". You will type this code:

Code: HTML
1
<input type="hidden" name="nickname" value="Mateo21" />


Nothing will appear on screen.
But in the target page, a variable $_POST['nickname'] will be created (corresponding to name). Its value will be "Mateo21" (corresponding to value)! :D

It sounds useless, but when you'll start creating forms you'll find it necessary soon enough ;)




Small exercise

We're going to practice on a check box. We'll ask the guest's favourite colour. When he will have chosen, we must be able to do 2 things:

1. We're going to write the guest's favourite colour (by means of a simple echo).
2. This colour will be made the check box's default choice.

Let's call up our memories with something we haven't seen since Part I: the functions that you can define by yourselves. We are going to define a function called defaultChecked that will return 'selected' if the colour given is the user's choice, or nothing if it's not the guest's favourite colour.

Let's stop chatting and start coding :D

Code: PHP
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
function defaultChecked($colour) // Function creation
{
$defaultValue= ''; // We create an empty variable (empty by default) that we will return at the end
    if (isset($_POST['colour'])) // If the guest chose a colour
    {
        if ($_POST['colour'] == $colour) // If the guest's colour corresponds to what we are actually processing
        {
            $defaultValue='selected="selected"'; // Then we modify the variable we will return and put selected to it
        }
    }

return $defaultValue; // We return selected if it was the colour chosen, nothing if it wasn't the good colour. 
}


// -------------- End of function ---------------


if (isset($_POST['colour'])) // We check if the guest already chose a colour
{
    echo '<p>Your favourite colour is: ' . htmlspecialchars($_POST['colour']) . '</p>';
}
?>


<p>What is your favourite colour?</p>

<form method="post">
<p>
    <select name="colour">
        <option value="Blue" <?php echo defaultChecked('Blue'); ?>>Blue</option>
        <option value="Brown" <?php echo defaultChecked('Brown'); ?>>Brown</option>
        <option value="Green" <?php echo defaultChecked('Green'); ?>>Green</option>
        <option value="Pink" <?php echo defaultChecked('Pink'); ?>>Pink</option>
    </select>
    <input type="submit" value="OK" />
</p>
</form>




I can imagine your face while looking at this code: o_O
On the one hand, I understand this code might scare you; on the other, just avoid telling me about it otherwise I could get really angry :devil:

Why? Because I "only" used a function, which is something I taught you in one of this PHP tutorial's first chapters!!!
It means that theoretically you should be able to understand all that.

Anyway, I'll explain how it works. I don't want to undergo any of your hostile reactions!
You can roughly forget about the beginning of the code. Just look after the "End of function" commentary. If the user has made a choice, then we display what the guest's favourite colour is.

Red alert: when you display a form's results, get used to applying a htmlspecialchars automatically. And when I say automatically, I mean ALWAYS, like each time, even in a check box or a hidden field, a guest can modify the source to put some HTML or javascript!


Then we display your simple form. As we want to reload the same page, I haven't put any action attribute.
For each option, I display what my function defaultChecked returns when I put the colour "Green" for instance. The function can return 'selected="selected"', in this case you display selected that will be the default choice, or might not return anything, which means it won't be a default choice.

If you're having problems understanding how my function works, I highly recommend that you read the function chapter again.
Don't hesitate to spend some time on this code to see how it works because I find it quite interesting. If you were able to understand this, you have understood everything :)



File sending

Did you know that you could also upload files thanks to forms?

You will need to read this section if you want your guests to send (or upload) images, programs or any other type of file to your website.

Two steps again:

1. The guest reaches your form and fills it out (indicating the file to upload). A simple HTML page is enough to create the form.
2. PHP receives the form's data and "saves" the files in one of the server's files, if it contains any.

Careful: if your file is big, the uploading time can be quite long. You'll have to tell your guest not to lose patience.


Before seeing how to process the file's uploading on the server with PHP, we are going to start by creating the form allowing to upload a file (a simple HTML page).

The Upload-file form



If ever your form offers your guests to upload a file, you need to add the following attribute enctype="multipart/form-data" to the tag <form>.

Code: HTML
1
2
3
<form action="upload_file.php" method="post" enctype="multipart/form-data">
    <p>Upload-file form</p>
</form>


Thanks to enctype, the guest's browser knows that it is about to upload files.

Once it's done, we can add a tag allowing to upload a file inside the form. It's a very simple tag like <input type="file" />. As usual, think about naming this form field (using the attribute name) for PHP to recognize the field later on.

Code: HTML
1
2
3
4
5
6
7
8
<form action="upload_file.php" method="post" enctype="multipart/form-data">
        <p>
                Upload-file form:<br />
                <input type="file" name="myfile" /><br />
                <input type="submit" value="Upload file" />
        </p>
</form>
<code type="html">


Enough :)

You can add some more standard fields to the form (text field, check boxes). You can also offer to upload several files at the same time.
In this case, we're going to stand with one field only (upload file) to stay simple.


Upload processing in PHP



As you may have noticed, the form aims at a PHP page called upload_file.php, on which the guest will be redirected after the form has been sent.

This is where it's starting to get important. We have to write the code of the page upload_file.php to process the file's uploading.

What do you mean by "processing the file's uploading"?
Is that OK if the file was sent on the server? What would PHP need to do?



Actually, the moment when the PHP page is executing, the file has been sent on the server but is stored in a temporary folder.
You are to decide whether you accept the file permanently or not. You can check if the file has the right extension for instance (if you ask for an image and you are sent ".txt", you must decline the file).

How do I know whether it's the right file or not?


There is a $_FILES['field_name'] variable created for each file uploaded. In our case, the variable will be called $_FILES['myfile'].
This variable is a spreadsheet containing several pieces of information regarding the file:

VariableMeaning
$_FILES['myfile']['name'] Contains the name of the file uploaded by the guest
$_FILES['myfile']['type'] Indicates the type of the uploaded file. If it's a gif image for instance, the type will be image/gif.
$_FILES['myfile']['size'] Indicates the size of the uploaded file. Be careful: this size is in bytes. Around 1000 bytes will be needed to make 1kB, and 1000 000 bytes to make 1 MB. Note that the sending size is limited by PHP. As a default value, it is impossible to upload files bigger than 8 Mb.
$_FILES['myfile']['tmp_name'] Right after being uploaded, the file is stored in a temporary directory on the server, while waiting for your PHP script to decide whether it accepts to store it permanently or not. This variable contains the file's temporary location (this is handled by PHP).
$_FILES['myfile']['error'] Contains an error code allowing to know if the sending was done properly or if there was a problem, and if that's the case, which one.
If there wasn't any error, the value of the variable is 0.




If you have put a second upload-file field in your form, there will be a second variable $_FILES['name_of_your_other_field'] outlined the same way as the spreadsheet we've just seen.
$_FILES['name_of_your_other_field']['size'] will also contain the size of the second file, and so on.


Let's make the following checks to decide whether we accept the file or not:

1. First of all, check if the guest really uploaded a file (by testing the variable $_FILES['myfile'] with isset). If there's no sending error (with $_FILES['myfile']['error'])
2. Check if the size of the file doesn't exceed 1 MB for instance (around 1 000 000 bytes) with $_FILES['myfile']['size']
3. Check if the file's extension is authorized (you definitely have to forbid anyone from uploading PHP files, if not they could execute scripts on your server!).
In our case, we will authorize images only (.png, .jpg, .jpeg and .gif files).
To do so we will scan the variable $_FILES['myfile']['name'].


A series of tests will be carried out in our page upload_file.php

1/ Test if the file was uploaded



We start by testing if the variable $_FILES['myfile'] exists with isset() to check whether a file was uploaded.
We also have to check THAT there is no sending error.
Code: PHP
1
2
3
4
5
6
7
<?php
// Let's test if the file was uploaded and that there is no error
if (isset($_FILES['myfile']) AND $_FILES['myfile']['error'] == 0)
{
 
}
?>


2/ Check the size of the file



We want to prevent the file from exceeding 1 MB, around 1 000 000 bytes (I'm rounding off to make things simpler).
As a consequence, we must test $_FILES['myfile']['size']:

Code: PHP
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?php
// Let's test if the file was uploaded and that there is no error
if (isset($_FILES['myfile']) AND $_FILES['myfile']['error'] == 0)
{
        // Let's test if the file is not too big
        if ($_FILES['myfile']['size'] <= 1000000)
        {
 
        }
}
?>


3/ Check the file's extension



The file's extension can be retrieved in a variable through this code:

Code: PHP
1
2
3
4
<?php
$fileinfo = pathinfo($_FILES['myfile']['name']);
$extension_upload = $fileinfo['extension'];
?>



The function pathinfo returns an array containing, among other things, the file's extension in $fileinfo['extension']. We store this in the variable $extension_upload.

Once you have retrieved the extension, we can compare it to an authorized extensions spreadsheet (an array) and check if the extension recovered is really part of the authorized extensions by means of the function in_array().

Phew! That finally gives us:

Code: PHP
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<?php
// Let's test if the file was uploaded and that there is no error
if (isset($_FILES['myfile']) AND $_FILES['myfile']['error'] == 0)
{
        // Let's test if the file is not too big
        if ($_FILES['myfile']['size'] <= 1000000)
        {
                // Let's test if the extension is authorized
                $fileinfo = pathinfo($_FILES['myfile']['name']);
                $extension_upload = $fileinfo['extension'];
                $authorized_extensions = array('jpg', 'jpeg', 'gif', 'png');
                if (in_array($extension_upload, $authorized_extensions))
                {
                
                }
        }
}
?>



4/ Validate the file's upload



If everything is fine, the file is accepted by calling move_uploaded_file().
This function takes 2 parameters:

  • The temporary name of the file (we have it with $_FILES['myfile']['tmp_name'])
  • The path and name under which the file will be stored permanently. We can use the file's original name $_FILES['myfile']['name'] or generate a name randomly.


I suggest that we place the file in a subfolder "uploads".
We'll keep the same file name as the original one. Since $_FILES['myfile']['name'] contains the entire path to the original file (C:\folder\file.png for instance), we'll have to extract the name from the file. We can use the function basename for that, which will only return "file.png" :)

Code: PHP
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
<?php
// Let's test if the file was uploaded and that there is no error
if (isset($_FILES['myfile']) AND $_FILES['myfile']['error'] == 0)
{
        // Let's test if the file is not too big
        if ($_FILES['myfile']['size'] <= 1000000)
        {
                // Let's test if the extension is authorized
                $fileinfo = pathinfo($_FILES['myfile']['name']);
                $extension_upload = $fileinfo['extension'];
                $authorized_extensions = array('jpg', 'jpeg', 'gif', 'png');
                if (in_array($extension_upload, $authorized_extensions))
                {
                        // We can validate the file and store it permanently
                        move_uploaded_file($_FILES['myfile']['tmp_name'], 'uploads/' . basename($_FILES['myfile']['name']));
                        echo "Upload completed!";
                }
        }
}
?>




When you'll put the script on the internet by means of a FTP software program, check that the folder "uploads" on the server exists and has the writing permissions. Under Filezilla, you must right-click on the folder and choose "Attributes of the file".
This will allow you to edit the folder's permissions (we talk about CHMOD). Set the permissions to 733, so that PHP will be able to place uploaded files in this folder.


This script is only a beginning, and you will certainly have to improve it. For instance, if the file's name contains spaces or accents it will pose a problem once you have sent it on the web. Besides, if somebody uploads a file bearing the same name as someone else's, the old one will be overwritten!

The solution generally consists in "choosing" ourselves the name of the file stored on the server rather than using the original name. You can do an incrementing counter:
1.png, 2.png, 3.jpg etc.

Bear in mind to be very careful on security. You ought to avoid that someone might upload PHP files on your server.


If you want to go further, I recommend that you read DHKold's tutorial on file upload by forms. It's more exhaustive than mine and will expalin certain details better than I could.

Have a nice reading ^^

Previous Chapter Contents Next Chapter

Tutorial's information

Back on top Back on top

Creation : : On 06/26/2007 10:23:18 AM
Last modification: : On 10/07/2008 01:00:07 AM
Progress : 0%
License : Unauthorized copy

Comments
Alert Validators