PHP Chapter 4 (Working with HTML Forms)

HTML Forms and PHP

If you know a little HTML, then you know that the FORM tags can be used to interact with your users. Things that can be added to a form are the likes of text boxes, radio buttons, check boxes, drop down lists, text areas, and submit buttons. A basic HTML form with a textbox and a Submit button looks like this:
<html>
<head>
<title>A BASIC HTML FORM</title>
</head>
<body>
<FORM NAME ="form1" METHOD =" " ACTION = "">
<INPUT TYPE = "TEXT" VALUE ="username">
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login">
</FORM>
</body>
</html>
We won't explain what all the HTML elements do, as this is a book on PHP. Some familiarity with the above is assumed. But we'll discuss the METHOD, ACTION and SUBMIT attributes in the form above, because they are important.
The above form can be found in the files you download. It's in the scripts folder, and is calledbasicForm.php. Use it as a template, if you like.
So, create the form above. Save your work as basicForm.php. (This name will be VERY important!) Start your server, and make sure the form loads ok in your browser. You should be able to see a text box and a Submit button. Here's what it should look like:
A Basic HTML Form

If a user comes to your site and has to login, for example, then you'll need to get the details from textboxes. Once you get the text that the user entered, you then test it against a list of your users (this list is usually stored on a database, which we'll see how to code for in a later section). First, you need to know about the HTML attributes METHOD, ACTION and SUBMIT.

PHP and the Method Attribute of HTML Forms

If you look at the first line of our form from the previous page, you'll notice a METHOD attribute:
<FORM NAME ="form1" METHOD =" " ACTION = "">
The Method attribute is used to tell the browser how the form information should be sent. The two most popular methods you can use are GET and POST. But our METHOD is blank. So change it to this:
<FORM NAME ="form1" METHOD ="GET" ACTION = "">
To see what effect using GET has, save your work again and then click the Submit button on your form. You should see this:
The GET Method of a HTML Form
The thing to notice here is the address bar. After basicForm.php, we have the following:
?Submit1=Login
This is a consequence of using the GET method. The data from the form ends up in the address bar. You'll see a question mark, followed by form data. In the image above, Submit1 was the NAME of the button, and Login was the VALUE of the button (the text on the button). This is what is being returned by the GET method. You use the GET method when the data you want returned is not crucial information that needs protecting.
You can also use POST as the Method, instead of GET.

PHP and the Post Attribute of HTML Forms

In the previous section, you saw what happened in the browser's address bar when you used the GET method for Form data. The alternative to GET is to use POST. Change the first line of your FORM to this:
<FORM NAME ="form1" METHOD ="POST" ACTION = "">
Close your browser down, and open it back up. Load your basicForm.php page again, and then click the button. Your address bar will then look like this:
The POST Method of a HTML Form
The ?Submit1=Login part from the previous section is now gone! That is because we used POST as the method. Using POST means that the form data won't get appended to the address in the address bar for all to see. We'll use both POST and GET throughout the book. But it depends on the project: if the data is not sensitive then use GET, otherwise use POST.
Another important attribute of the Form tag is Action. Without Action, your forms won't go anywhere!

PHP and the Action Attribute of HTML Forms

The Action attribute is crucial. It means, "Where do you want the form sent?". If you miss it out, your form won't get sent anywhere. You can send the form data to another PHP script, the same PHP script, an email address, a CGI script, or any other form of script.
In PHP, a popular technique is to send the script to the same page that the form is on – send it to itself, in other words. We'll use that technique first, but you'll see both techniques in action.
So you need to change the form you have been creating in the previous sections, the one that should be called basicForm.php. Locate the following, and amend the ACTION line to this:
<Form Name ="form1" Method ="POST" ACTION = "basicForm.php">
So we're going to be sending the form data to exactly the same page as the one we have loaded – to itself. We'll put some PHP on the page to handle the form data. But for now, save your work again and then click your submit button. You won't see anything different, but you shouldn't see any error message either!
Once your script has an Action attribute set, you can then Submit it.

PHP and the Submit Button of HTML Forms

The HTML Submit button is used to submit form data to the script mentioned in the ACTION attribute. Here's ours:
<Form Name ="form1" Method ="POST" ACTION = "basicForm.php">
So the page mentioned in the ACTION attribute is basicForm.php. To Submit this script, you just need a HTML Submit button:
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login">
You don't need to do anything special with a Submit button – all the submitting is done behind your back. As long as SUBMIT has an ACTION set, then your data will get sent somewhere. But the NAME attribute of the Submit buttons comes in very handy. You can use this Name to test if the form was really submitted, or if the user just clicked the refresh button. This is important when the PHP script is on the same page as the HTML form. Our Submit button is called "Submit1", but you can call it almost anything you like.
Now that you know about METHOD, ACTION, and SUBMIT, we can move on to processing the data that the user entered. First, how to get values from our text box.

PHP and Text Boxes on HTML Forms

If you've been following along from the previous sections then your basicForm.php now has a METHOD and ACTION set. We're going to use these to process text that a user has entered into a text box. The METHOD attribute tells you how form data is being sent, and the ACTION attribute tells you where it is being sent.
To get at the text that a user entered into a text box, the text box needs a NAME attribute. You then tell PHP the NAME of the textbox you want to work with. Our text box hasn't got a NAME yet, so changeyour HTML to this:
<INPUT TYPE = "Text" VALUE ="username" NAME = "username">
The NAME of our textbox is username. It's this name that we will be using in a PHP script.
To return data from a HTML form element, you use the following strange syntax:
$_POST['formElement_name'];
You can assign this to a variable:
$Your_Variable = $_POST['formElement_name'];
Before we explain all the syntax, add the following PHP script to the HTML code you have so far. Make sure to add it the HEAD section of your HTML (the part to add is in bold):
<html>
<head>
<title>A BASIC HTML FORM</title>
<?PHP
$username = $_POST['username'];
print ($username);
?>
</head>
Save your work again, and click the submit button to run your script. (Don't worry if you see an error message about "Undefined index". Click the button anyway.) You should see this appear above your text box:
Get the Username from the text box
Delete the text "username" from the textbox, and click the button again. Your new text should appear above the textbox. The text box itself, however, will still have "username" in it. This is because the text box is getting reset when the data is returned to the browser. The Value attribute of the text box is what is being displayed.
So how does it work?
The $_POST[ ] is an inbuilt function you can use to get POST data from a form. If you had METHOD = "GET" on your form, then you'd used this instead:
$username = $_GET['username'];
So you begin with a dollar sign ($) and an underscore character ( _ ). Next comes the METHOD you want to use, POST or GET. You need to type a pair of square brackets next. In between the square brackets, you type the NAME of your HTML form element – username, in our case.
$_POST['username'];
Of course, you need the semi-colon to complete the line.
Whatever the VALUE was for your HTML element is what gets returned. You can then assign this to a variable:
$username = $_POST['username'];
So PHP will look for a HTML form element with the NAME username. It then looks at the VALUE attribute for this form element. It returns this value for you to use and manipulate.
At the moment, all we're doing is returning what the user entered and printing it to the page. But we can use a bit of Conditional Logic to test what is inside of the variable. As an example, change your PHP to this:
$username = $_POST['username'];
if ($username == "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
We're now checking to see if the user entered the text "letmein". If so, the username is correct; if not, print another message.
Try it out an see what happens. When you first load the page, before you even click the button, you might see the text "You're not a member of this site" displayed above the textbox. That's because we haven't checked to see if the Submit button on the form was clicked.

PHP Submit buttons

In the previous section, you saw how to get text from a textbox when a Submit button on a form was clicked. However, when you first load the page the text still displays.
The reason why the text displays when the page is first loaded is because the script executes whether the button is clicked or not. This is the problem you face when a PHP script is on the same page as the HTML, and is being submitted to itself in the ACTION attribute.
To get round this, you can do a simple check using another IF Statement. What you do is to check if the Submit button was clicked. If it was, then run your code. To check if a submit button was clicked, use this:
if ( isset( $_POST['Submit1'] ) ) { }
Now that looks a bit messy! But it actually consists of three parts:
if ( ) { }
isset( )
$_POST['Submit1']
You know about the if statement. But in between the round brackets, we have isset( ). This is an inbuilt function that checks if a variable has been set or not. In between the round brackets, you type what you want isset( ) to check. For us, this is $_POST['Submit']. If the user just refreshed the page, then no value will be set for the Submit button. If the user did click the Submit button, then PHP will automatically return a value. Change you script from the previous page to the following and try it out:
if (isset($_POST['Submit1'])) {
$username = $_POST['username'];
if ($username == "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
}
Make a note of where all those messy round, square and curly brackets are. Miss one out and you'll get an error!

The HTML ACTION attribute and PHP

You don't have to submit your form data to the same PHP page, as we've been doing. You can send it to an entirely different PHP page. To see how it works, try this:
Create the following page, and call it basicForm2.php. This is your HTML. Notice the ACTION attribue.
<html>
<head>
<title>A BASIC HTML FORM</title>
</head>
<body>
<Form name ="form1" Method ="POST" Action ="submitForm.php">
<INPUT TYPE = "TEXT" VALUE ="username" Name ="username">
<INPUT TYPE = "Submit" Name = "Submit1" VALUE = "Login">
</FORM>
</body>
</html>

Now create the following page, and call it submitForm.php:
<?PHP
$username = $_POST['username'];
if ($username == "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
?>
In the PHP script above, notice how there's no HTML tags. And we've left out the code that checks if the Submit button was clicked. That's because there's no PHP left in the first page. The code only gets executed IF the Submit is clicked.
Posting form data to a different PHP script is a way to keep the HTML and PHP separate. But there is a problem with it, which you will have noticed: the script gets executed on a new page. That means your form will disappear!
We'll keep the PHP and HTML together. But there will be times when you do want to send form data to a different PHP page,

PHP Data Retention

In the previous sections, you've been following along and building up a HTML form. You've learned how to get the text from a text box on a form, but there is a problem.
When the basicForm.php form is submitted, the details that the user entered get erased. You're left with the VALUE that was set in the HTML. For us, username kept appearing in the text box when the button was clicked. You can keep the data the user entered quite easily.
Your script should now look like the one in the link below. If not copy and paste this script, and test it out on your server. (Save the script as basicForm.php.)
The basicForm.php script
If you look at the VALUE attribute of the text box in the HTML from the above script, you'll see that it's set to "username". Because the form gets posted back to itself, this value will keep re-appearing in the textbox when the page is submitted. Worse, if you've left the Value attributes empty then everything the user entered will disappear. This can be very annoying, if you're asking the user to try again. Better is to POST back the values that the user entered.
To post the details back to the form, and thus keep the data the user has already typed out, you can use this:
VALUE="<?PHP print $username ; ?>"
In other words, the VALUE attribute is now a PHP line of code. The line of code is just this:
<?PHP
print $username ;
?>
It's a bit hard to read, because it's all on one line.
You also need to amend your PHP code in the HEAD section to include an else statement:
if (isset($_POST['Submit1'])) {
$username = $_POST['username'];
if ($username == "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
}
else {
$username ="";
}
In the else statement at the end, we're just setting the value of the variable called $username for when the button is NOT clicked, i.e. when the page is refreshed.
However, there are some security issues associated with textboxes (and other form elements). So we'll see a more secure way to handle these in a later section.
But our new line of HTML for our textbox reads like this:
<INPUT TYPE = 'TEXT' Name ='username' VALUE="<?PHP print $username ; ?>">
In other words, we're now printing out the VALUE attribute with PHP code.
Now that you know a few things about getting values from HTML forms, here's a few exercise
Exercise
Add two text boxes and a Submit button to a HTML form. Invite the user to enter a first name and surname. When the button is clicked, print out the person's full name. Don't worry about what is in the text boxes after the button is clicked.
Exercise
Using the same form as the previous exercise, display the first name and surname in the textboxes, instead of printing them out.
Exercise
Suppose your web site has only 5 users. Create a HTML form to check if a visitor is one of the 5 users. Display a suitable message.
A Radio Button is a way to restrict users to having only one choice. Examples are : Male/Female, Yes/No, or answers to surveys and quizzes.
Here's a simple from with just two radio buttons and a Submit button:
A Form with Radio Buttons
You can find the code for the page above in the files you downloaded, in the scripts folder. The file is called radioButton.php. Open it up in your text editor. If you want to copy and paste it, click below.
The Radio Button Form
Make sure you save your work as radioButton.php, as that's where we're posting the Form – to itself.
To get the value of a radio button with PHP code, again you access the NAME attribute of the HTML form elements. In the HTML above, the NAME of the Radio buttons is the same – "gender". The first Radio Button has a value of "male" and the second Radio Button has a value of female. When you're writing your PHP code, it's these values that are returned. Here's some PHP code. Add it to the HEAD section of your HTML:
<?PHP
$selected_radio = $_POST['gender'];
print $selected_radio;
?>
This is more or less the same code as we used for the text box! The only thing that's changed (apart from the variable name) is the NAME of the HTML form element we want to access – "gender". The last line just prints the value to the page. Again, though, we can add code to detect if the user clicked the Submit button:
if (isset($_POST['Submit1'])) {
$selected_radio = $_POST['gender'];
print $selected_radio;
}
Again, this is the same code you saw earlier – just access the form element called 'Submit1' and see if it is set. The code only executes if it is.
Try out the code. Select a radio button and click Submit button. The choice you made is printed to the page - either "male" or "female". What you will notice, however, when you try out the code is that the dot disappears from your selected radio button after the Submit is clicked. Again, PHP is not retaining the value you selected. The solution for radio Buttons, though, is a little more complex than for text boxes
Radio buttons have another attribute - checked or unchecked. You need to set which button was selected by the user, so you have to write PHP code inside the HTML with these values - checked or unchecked. Here's one way to do it:
The PHP code:
<?PHP
$male_status = 'unchecked';
$female_status = 'unchecked';
if (isset($_POST['Submit1'])) {
$selected_radio = $_POST['gender'];
if ($selected_radio = = 'male') {
$male_status = 'checked';
}
else if ($selected_radio = = 'female') {
$female_status = 'checked';
}
}
?>
The HTML FORM code:
<FORM name ="form1" method ="post" action ="radioButton.php">
<Input type = 'Radio' Name ='gender' value= 'male'
<?PHP print $male_status; ?>
>Male
<Input type = 'Radio' Name ='gender' value= 'female'
<?PHP print $female_status; ?>
>Female
<P>
<Input type = "Submit" Name = "Submit1" VALUE = "Select a Radio Button">
</FORM>
Did we say a little more complex? OK, it's much more complex than any code you've written so far! Have a look at the PHP code inside the HTML first:
<?PHP print $female_status; ?>
This is just a print statement. What is printed out is the value inside of the variable. What is inside of the variable will be either the word "checked" or the word "unchecked". Which it is depends on the logic from our long PHP at the top of the page. Let's break that down.
First we have two variables at the top of the code:
$male_status = 'unchecked';
$female_status = 'unchecked';
These both get set to unchecked. That's just in case the page is refreshed, rather than the Submit button being clicked.
Next we have our check to see if Submit is clicked:
if (isset($_POST['Submit1'])) {
}
Exactly the same as before. As is the next line that puts which radio button was selected into the variable:
$selected_radio = $_POST['gender'];
We then need some conditional logic. We need to set a variable to "checked", so we have an if, else … if construction:
if ($selected_radio == 'male') {
}
else if ($selected_radio == 'female') {
}
All we're doing is testing what is inside of the variable called $selected_radio. If it's 'male' do one thing; if it's 'female', do another. But look at what we're doing:
if ($selected_radio == 'male') {
$male_status = 'checked';
}
else if ($selected_radio = = 'female') {
$female_status = 'checked';
}
If the 'male' button was clicked then set the $male_status variable to a value of 'checked'. If the 'female' option button was clicked then set the $female_status variable to a value of 'checked'.
So the code works because of the values inside of two variables: $male_status and$female_status.
Yes, the code is very messy – but radio Buttons can be a quite tricky, when you want to retain the value of the selected item. Speaking of tricky – checkboxes are up next!

PHP and HTML Checkboxes

Like Radio buttons, checkboxes are used to give visitors a choice of options. Whereas Radio Buttons restrict users to only one choice, you can select more than one option with Checkboxes.
Here's a page that asks users to choose which course books they want to order:
A Form with Checkboxes
As you can see, five items can be selected. Only three are chosen at the moment. When the button is clicked you, as the programmer, want to do at least two things: record which checkboxes were ticked, and have PHP "remember" which items were chosen, just in case of errors.
You don't want the ticks disappearing from the checkboxes, if the user has failed to enter some other details incorrectly. We saw with Radio Buttons that this can involve some tricky coding. The same is true for checkboxes. Let's have a look at one solution to the problem.
Because the code is a little more complex, we've included it in the files you downloaded. The script you're looking for is checkboxes.php, and is in the scripts folder. Open it up and take a look at the code. Here it is in full, if you want to copy and paste it:
The Checkboxes Script
Note one thing about the HTML checkbox elements: they all have different NAME values (ch1, ch2 ch3, etc). When we coded for the Radio Buttons, we gave the buttons the same NAME. That's because only one option can be selected with Radio Buttons. Because the user can select more than one option with Checkboxes, it makes sense to give them different NAME values, and treat them as separate entities (but some advocate treating them just like Radio Buttons).
In your PHP code, the technique is to check whether each checkbox element has been checked or not. It's more or less the same as for the radio Buttons. First we set up five variable and set them all the unchecked, just like we did before:
$ch1 = 'unchecked';
$ch2 = 'unchecked';
$ch3 = 'unchecked';
$ch4 = 'unchecked';
$ch5 = 'unchecked';
The next thing is the same as well: check to see if the Submit button was clicked:
if (isset($_POST['Submit1'])) {
}
Inside of this code, however, we have another isset( ) function:
if ( isset($_POST['ch1']) ) {
}
This time, we're checking to see if a checkbox was set. We need to do this because of a peculiarity of HTML checkboxes. If they are not ticked, they have no value at all, so nothing is returned! If you try the code without checking if the checkboxes are set, then you'll have to deal with a lot of "Undefined" errors.
If the checkbox is ticked, though, it will return a value. And so the isset( ) function will be true. If the isset( ) function is true, then our code inside of the if statement gets executed:
if ($ch1 == 'net') {
$ch1 = 'checked';
}
This is yet another If Statement! But we're just checking the value of a variable. We need to know what is inside of it. This one says, "If the value inside of the variable called $ch1 is 'net' then execute some code.
The code we need to execute is to put the text 'checked' inside of the variable called $ch1. The rest of the if statements are the same – one for each checkbox on the form.
The last thing we need to do is to print the value of the variable to the HTML form:
<Input type = 'Checkbox' Name ='ch1' value ="net"
<?PHP print $ch1; ?>
>Visual Basic .NET
Again, this is the same code you saw with the Radio Buttons. The PHP part is:
<?PHP print $ch1; ?>
So we're just printing what is inside of the variable called $ch1. This will either be "unchecked" or "checked",
There are other solution for checkboxes, but none seem simple! The point here, though, is that to get the job done we used Conditional Logic.

How to validate checkboxes using JavaScript

Another way to deal with checkboxes, though, is with some JavaScript. The following script was sent to us by Tapan Bhanot. It uses JavaScript to validate the checkboxes before sending it to a PHP script. Note how the checkboxes all have the same name on the HTML form, and that it is being posted to a PHP script called step2.php:
View Tapan's script (opens in a new window)
You'll learn more about dealing with HTML forms as we go along. For now, we'll leave the subject, and move on. It's a bit of a bumpy ride in the next part, though, as we're tackling loops!

Comments