You are on page 1of 26

Creating and using forms

HTML Forms
HTML forms are used to pass data to a server. A form can contain input elements like text fields, checkboxes, radio-buttons, submit buttons and more. A form can also contain select lists, textarea, fieldset, legend, and label elements. HTML form elements have three attributes in common.
1. name 2. id 3. value

The id attribute is not required right now but will come in handy when you start using JavaScript. Each element should have a unique name and id. We will use the elements name to access its value in PHP. Forms are a vital tool for the webmaster to receive information from the web surfer, such as: their name, email address, credit card, etc. A form will take input from the viewer and depending on your needs, you may store that data into a file, place an order, gather user statistics, register the person to your web forum, or maybe subscribe them to your weekly newsletter.

Text Fields
The <input> has a few attributes that we should be aware of.

type - Determines what kind of input field it will be. Possible choices are text, submit, and password. name - Assigns a name to the given field so that you may reference it later. size - Sets the horizontal width of the field. The unit of measurement is in blank spaces. maxlength - Dictates the maximum number of characters that can be entered.

HTML Code:
<form method="post" action="mailto:youremail@email.com"> Name: <input type="text" size="10" maxlength="40" name="name"> <br /> Password: <input type="password" size="10" maxlength="10" name="password"> </form>

Input Forms:
Name: Password:

Do not use the password feature for security purposes. The data in the password field is not encrypted and is not secure in any way. we can also add a destination for this information and specify how we want it to travel to that place. Adding the following attributes to your <form> will do just this.

method - We will only be using the post functionality of method, which sends the data without displaying any of the information to the visitor. action - Specifies the URL to send the data to. We will be sending our information to a fake email address.

HTML Code:
<form method="post" action="mailto:youremail@email.com"> Name: <input type="text" size="10" maxlength="40" name="name"> <br /> Password: <input type="password" size="10" maxlength="10" name="password"><br /> <input type="submit" value="Send"> </form>

Email Forms:
Name: Password:

HTML Radio Buttons


Radio buttons are a popular form of interaction. You may have seen them on quizzes, questionnaires, and other web sites that give the user a multiple choice question. Below are a couple attributes you should know that relate to the radio button.

value - specifies what will be sent if the user chooses this radio button. Only one value will be sent for a given group of radio buttons (see name for more information). name - defines which set of radio buttons that it is a part of. Below we have 2 groups: shade and size.

HTML Code:
<form method="post" action="mailto:youremail@email.com"> What kind of shirt are you wearing? <br /> Shade: <input type="radio" name="shade" value="dark">Dark <input type="radio" name="shade" value="light">Light <br /> Size: <input type="radio" name="size" value="small">Small <input type="radio" name="size" value="medium">Medium <input type="radio" name="size" value="large">Large <br />

<input type="submit" value="Email Myself"> </form>

Radios:
What kind of shirt are you wearing? Shade: Size: Dark Small Light Medium Large

If you change the email address to your own and "Email Myself" then you should get an email with "shade=(choice) size=(choice)".

HTML Check Boxes


Check boxes allow for multiple items to be selected for a certain group of choices. The check box's name and value attributes behave the same as a radio button.

HTML Code:
<form method="post" action="mailto:youremail@email.com"> Select your favorite cartoon characters. <input type="checkbox" name="toon" value="Goofy">Goofy <input type="checkbox" name="toon" value="Donald">Donald <input type="checkbox" name="toon" value="Bugs">Bugs Bunny <input type="checkbox" name="toon" value="Scoob">Scooby Doo <input type="submit" value="Email Myself"> </form>

Check Boxes:
Select the 2 greatest toons. Goofy Donald Bugs Bunny Scooby Doo

HTML Drop Down Lists


Drop down menus are created with the <select> and <option> tags. <select> is the list itself and each <option> is an available choice for the user.

HTML Code:
<form method="post" action="mailto:youremail@email.com"> College Degree? <select name="degree">

<option>Choose One</option> <option>Some High School</option> <option>High School Degree</option> <option>Some College</option> <option>Bachelor's Degree</option> <option>Doctorate</option> <input type="submit" value="Email Yourself"> </select> </form>

Drop Down Lists:


Education?

HTML Selection Forms


Yet another type of form, a highlighted selection list. This form will post what the user highlights. Basically just another type of way to get input from the user. The size attribute selects how many options will be shown at once before needing to scroll, and the selected option tells the browser which choice to select by default.

HTML Code:
<form method="post" action="mailto:youremail@email.com"> Musical Taste <select multiple name="music" size="4"> <option value="emo" selected>Emo</option> <option value="metal/rock" >Metal/Rock</option> <option value="hiphop" >Hip Hop</option> <option value="ska" >Ska</option> <option value="jazz" >Jazz</option> <option value="country" >Country</option> <option value="classical" >Classical</option> <option value="alternative" >Alternative</option> <option value="oldies" >Oldies</option> <option value="techno" >Techno</option> </select> <input type="submit" value="Email Yourself"> </form>

Selection Forms:
Musical Taste

HTML Upload Forms


We have an entire upload example here, PHP File Upload. The HTML code for the upload form does nothing more than create an interface for the user to see and work with.

An upload form consists of three basic parts. The first being a hidden field. This hidden field does nothing more than limit the allowed file size of our uploaded file. The second part is the input field itself. In this field, the user has the option to type in the full local URL of the file or he/she may click the browse button to thumb through directory after directory. HTML codes this automatically when we place the type="file" attribute within the input tag. For uploading a file we should use the attribute enctype=multipart/formdat

HTML Code:
<input type="hidden" name="MAX_FILE_SIZE" value="100" /> <input name="file" type="file" />

Upload Form:

HTML Text Areas


Text areas serve as an input field for viewers to place their own comments onto. Forums and the like use text areas to post what you type onto their site using scripts. For this form, the text area is used as a way to write comments to somebody. Rows and columns need to be specified as attributes to the <textarea> tag. Rows are roughly 12pixels high, the same as in word programs and the value of the columns reflects how many characters wide the text area will be. i.e. The example below shows a text area 5 rows tall and 20 characters wide. Another attribute to be aware of is the wrap. Wrap has 3 values.

wrap=
o o o

"off" "virtual" "physical"

Virtual means that the viewer will see the words wrapping as they type their comments, but when the page is submitted to you, the web host, the document sent will not have wrapping words. Physical means that the text will appear both to you, the web host, and the viewer including any page breaks and additional spaces that may be inputed. The words come as they are. Off of course, turns off word wrapping within the text area. One ongoing line.

HTML Code:
<form method="post" action="mailto:youremail@email.com"> <textarea rows="5" cols="20" wrap="physical" name="comments"> Enter Comments Here </textarea> <input type="submit" value="Email Yourself"> </form>

Text Area:
Enter Comments Here

Also note that any text placed between the opening and closing textarea tags will show up inside the text area when the browser views it.

GET vs POST methods


There are two ways the browser client can send information to the web server.

The GET Method The POST Method

Before the browser sends the information, it encodes it using a scheme called URL encoding. In this scheme, name/value pairs are joined with equal signs and different pairs are separated by the ampersand.

name1=value1&name2=value2&name3=value3

Spaces are removed and replaced with the + character and any other nonalphanumeric characters are replaced with a hexadecimal values. After the information is encoded it is sent to the server.

The GET Method

The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character.

http://www.test.com/index.htm?name1=value1&name2=value2

The GET method produces a long string that appears in your server logs, in the browser's Location: box.

The GET method is restricted to send upto 1024 characters only.

Never use GET method if you have password or other sensitive information to be sent to the server.

GET can't be used to send binary data, like images or word documents, to the server.

The data sent by GET method can be accessed using QUERY_STRING environment variable.

The PHP provides $_GET associative array to access all the sent information using GET method.

Try out following example by putting the source code in test.php script.

<?php if( $_GET["name"] || $_GET["age"] ) { echo "Welcome ". $_GET['name']. "<br />";

echo "You are ". $_GET['age']. " years old."; exit(); } ?> <html> <body> <form action="<?php $_PHP_SELF ?>" method="GET"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html>

The POST Method

The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING. The POST method does not have any restriction on data size to be sent. The POST method can be used to send ASCII as well as binary data. The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure. The PHP provides $_POST associative array to access all the sent information using GET method. Try out following example by putting the source code in test.php script. <?php if( $_POST["name"] || $_POST["age"] )

{ echo "Welcome ". $_POST['name']. "<br />"; echo "You are ". $_POST['age']. " years old."; exit(); } ?> <html> <body> <form action="<?php echo $_SERVER[PHP_SELF] ?>" method="POST"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> The $_REQUEST variable The PHP $_REQUEST variable contains the contents of both $_GET, $_POST, and $_COOKIE. We will discuss $_COOKIE variable when we will explain about cookies. The PHP $_REQUEST variable can be used to get the result from form data sent with both the GET and POST methods. Try out following example by putting the source code in test.php script. <?php if( $_REQUEST["name"] || $_REQUEST["age"] ) { echo "Welcome ". $_REQUEST['name']. "<br />"; echo "You are ". $_REQUEST['age']. " years old.";

exit(); } ?> <html> <body> <form action="<?php echo $_SERVER[PHP_SELF] ?>" method="POST"> Name: <input type="text" name="name" /> Age: <input type="text" name="age" /> <input type="submit" /> </form> </body> </html> Here $_PHP_SELF variable contains the name of self script in which it is being called.

Validating form input


JavaScript Form Validation
JavaScript can be used to validate data in HTML forms before sending off the content to a server. Form data that typically are checked by a JavaScript could be:

has the user left required fields empty? has the user entered a valid e-mail address? has the user entered a valid date? has the user entered text in a numeric field?

Required Fields
The function below checks if a field has been left empty. If the field is blank, an alert box alerts a message, the function returns false, and the form will not be submitted:

function validateForm() { var x=document.forms["myForm"]["fname"].value; if (x==null || x=="") { alert("First name must be filled out"); return false; } }

The function above could be called when a form is submitted:

Example
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post"> First name: <input type="text" name="fname"> <input type="submit" value="Submit"> </form> We can use regular expressions for validating the form input in javascript..

Regular Expressions
A regular expression is a pattern that specifies a list of characters. In this section, we will look at how those characters are specified.

RegExp Object
A regular expression is an object that describes a pattern of characters. Regular expressions are used to perform pattern-matching and "search-and-replace" functions on text.

Syntax
var patt=new RegExp(pattern,modifiers); or more simply: var patt=/pattern/modifiers;

pattern specifies the pattern of an expression modifiers specify if a search should be global, case-sensitive, etc.

Modifiers
Modifiers are used to perform case-insensitive and global searches:
Modifier i g M Description Perform case-insensitive matching Perform a global match (find all matches rather than stopping after the first match) Perform multiline matching

Brackets
Brackets are used to find a range of characters:
Expression [abc] [^abc] [0-9] [A-Z] [a-z] [A-z] [adgk] [^adgk] Description Find any character between the brackets Find any character not between the brackets Find any digit from 0 to 9 Find any character from uppercase A to uppercase Z Find any character from lowercase a to lowercase z Find any character from uppercase A to lowercase z Find any character in the given set Find any character outside the given set

(red|blue|green) Find any of the alternatives specified

Metacharacters
Metacharacters are characters with a special meaning:

Metacharacter . \w \W \d \D \s \S \b \B \0 \n \f \r \t \v \xxx \xdd \uxxxx

Description Find a single character, except newline or line terminator Find a word character Find a non-word character Find a digit Find a non-digit character Find a whitespace character Find a non-whitespace character Find a match at the beginning/end of a word Find a match not at the beginning/end of a word Find a NUL character Find a new line character Find a form feed character Find a carriage return character Find a tab character Find a vertical tab character Find the character specified by an octal number xxx Find the character specified by a hexadecimal number dd Find the Unicode character specified by a hexadecimal number xxxx

Quantifiers
Quantifier Description

n+ n* n? n{X} n{X,Y} n{X,} n$ ^n ?=n ?!n

Matches any string that contains at least one n Matches any string that contains zero or more occurrences of n Matches any string that contains zero or one occurrences of n Matches any string that contains a sequence of X n's Matches any string that contains a sequence of X to Y n's Matches any string that contains a sequence of at least X n's Matches any string with n at the end of it Matches any string with n at the beginning of it Matches any string that is followed by a specific string n Matches any string that is not followed by a specific string n

Now we will see how to make regular expressions for validating the form input. Let us consider an example for validating the username in from. First the constraints for username are 1.The length of the username should not be less than 4 2. The starting character should be a alphabet or underscore. 3. From the second character the username may be a combination of alphabets or numbers or underscore. The regular expression is /^[a-zA-Z_][a-zA-Z_0-9]{3,20}$/ The first [a-zA-Z_] allows the first character should be a alphabet or underscore. Next [a-zA-Z_0-9] allows alphabets or numbers or underscores a minimum length of 3 to max length of 20. Similarly password regular expression is / ^[A-Za-z0-9!@#$%^&*()_]{6,20}$/

/^([\w-]+(?:\.[\w-]+)*)@((?:[\w]+\.)*\w[\w-]
And for email is

{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
Consider the following example for validating a form.
script type="text/javascript"> var ck_name = /^[A-Za-z0-9 ]{3,20}$/; var ck_email = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-] {0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i var ck_username = /^[A-Za-z0-9_]{1,20}$/; var ck_password = /^[A-Za-z0-9!@#$%^&*()_]{6,20}$/; function validate(form){ var name = form.name.value; var email = form.email.value; var username = form.username.value; var password = form.password.value; var gender = form.gender.value; var errors = []; if (!ck_name.test(name)) { errors[errors.length] = "You valid Name ."; } if (!ck_email.test(email)) { errors[errors.length] = "You must enter a valid email address."; } if (!ck_username.test(username)) { errors[errors.length] = "You valid UserName no special char ."; } if (!ck_password.test(password)) { errors[errors.length] = "You must enter a valid Password "; } if (gender==0) { errors[errors.length] = "Select Gender"; } if (errors.length > 0) { reportErrors(errors); return false; } return true; } function reportErrors(errors){ var msg = "Please Enter Valide Data...\n"; for (var i = 0; i<errors.length; i++) { var numError = i + 1; msg += "\n" + numError + ". " + errors[i]; } alert(msg); } </script>

<form method="post" action="account.php" onSubmit="return validate(this);" name="form"> Name:<input type=text name=name/><br/>

Email:<input type=text name=email/><br/> Username:<input type=text name=username/><br/> Password:<input type=password name=password/><br/> Gender:<input type=radio name=gender value=male>Male<input type=radio name=gender value=female/> Female<br/> <input type=submit value=Register/><input type=reset value=Cancel/> </form>

Working with multiple forms and from submissions


Processing form data in PHP is significantly simpler than in most other Web programming languagesa fact you're undoubtedly already aware of if you've been using the language for a while. This simplicity and ease of use makes it possible to do some fairly complex things with forms...including the topic of today's discussion, handling different actions through multiple submit buttons in the same form.

Why multiple submits?


Depending on which button was clicked, the data entered in the form was processed in a different way Since a form can only have a single action, the same PHP script had to handle all four tasks, by identifying which button had been clicked and executing the appropriate code branch. Thus, a need arose for a single form carrying multiple submit buttons, and a formprocessing script with the intelligence to distinguish between each one.

A single-button form
Consider the following example. <html><head>Single-button form</head> <body> <form action="processor.php" method="post"> s Enter a number: <input type="text" name="number" size="3"> <br> <input type="submit" name="submit"> </form> </body> </html> And here is the processor.php script that gets invoked on submission:

<?php // check for submission // retrieve value from posted data if ($_POST['submit']) { echo "You entered the number " . $_POST['number']; } ?> When a form is submitted to a PHP script, PHP automatically creates a special $_POST or $_GET associative array, depending on which method of submission was used (I'll assume POST throughout this tutorial). Values entered into the form input fields are automatically converted to key-value pairs in this array and can then be accessed using regular array notation. Pay special attention to how the submit button is handled in the above script. When the form is submitted, the submit button itself becomes an element in the $_POST array, with a key corresponding to its "name". This is clearly visible by adding the line: print_r($_POST); to the end of the PHP script above. You can look inside the array and clearly see the correspondence between the form controls and their PHP representations.

Handling multi button forms Branching with if/else


Let's now make things a bit more complicated by adding a second submit button to the form: <html><head>Multi-button form</head> <body> <form action="processor.php" method="post"> Enter a number: <input type="text" name="number" size="3"> <br> <input type="submit" name="add" value="Add 10"> <input type="submit" name="subtract" value="Subtract 10"> </form> </body> </html> Since both submit buttons will invoke the same PHP form processor, that PHP script must be revised to "know" which one was clicked so it can respond appropriately. Since you already know that the submit button appears in the $_POST PHP array and is keyed by its "name" attribute, it's simple to (1) give each submit button in the form a unique name and

(2) write a simple "if" test at the top of the PHP form processor to see which of the two keys appears in the $_POST array and branch the code appropriately. That's exactly what the script below does:<?php // check which button was clicked // perform calculation if ($_POST['add']) { echo $_POST['number'] . " + 10 = " . ($_POST['number']+10); } else if ($_POST['subtract']) { echo $_POST['number'] . " - 10 = " . ($_POST['number']-10); } ?> If you have a bunch of submits, a good idea is to use a switch/case statement to handle the different code branches more efficiently.

Branching with switch/case


In the previous example, I distinguished between buttons by using different name attributes for the submit buttons in the form. An alternative is giving all the submit buttons the same name, but different values: <html><head>Multi-button from with switch/case</head> <body> <form action="processor.php" method="post"> Enter a number: <input type="text" name="number_1" size="3"> <br> Enter another number: <input type="text" name="number_2" size="3"> <br> <input type="submit" name="calculate" value="add"> <input type="submit" name="calculate" value="subtract"> <input type="submit" name="calculate" value="multiply"> </form> </body> </html> The processing script needs to check the value of the $_POST['calculate'] element, and branch the code appropriately. The most efficient way to do this is with a switch-case statement, as follows: <?php // branch on the basis of 'calculate' value switch ($_POST['calculate']) {

// if calculate => add case 'add': echo $_POST['number_1'] . " + " . $_POST['number_2'] . " = " . ($_POST['number_1']+$_POST['number_2']); break; // if calculate => subtract case 'subtract': echo $_POST['number_1'] . " - " . $_POST['number_2'] . " = " . ($_POST['number_1']$_POST['number_2']); break; // if calculate => multiply case 'multiply': echo $_POST['number_1'] . " x " . $_POST['number_2'] . " = " . ($_POST['number_1']*$_POST['number_2']); break; } ?> Depending on which button gets clicked, the appropriate value is passed to the processing script and the corresponding "case" block is invoked. If you have a large number of submit buttons to deal with, this approach is easier to read and understand than multiple if-else blocks.

Using graphical submit buttons


A minor twist in the tale comes if you use a graphical submit button, as in the following simple form: <html><head>Graphical submit button</head> <body> <form action="processor.php" method="post"> Search for: <input type="text" name="q"> <input type="image" name="go" src="/images/go.gif"> </form> </body> </html> When this form is sent to PHP for processing, look what the $_POST array contains: Array ( [q] => magpie [go_x] => 13

[go_y] => 13 ) Because it's a graphical button, PHP actually tracks the mouse coordinates of the mouse click and creates two elements in the result array to store those coordinates. The elements are named [button_name]_x and [button_name]_y respectively. Why is this important? Well if you'd been using an if() test keyed on the submit control's "name" the test would have failed because instead of creating a single element accessible through $_POST['go'], PHP actually created two elements named $_POST['go_x'] and $_POST['go_y'] respectively. Make a mental note of this for future reference; it might save you some time when things don't work as expected. So now, what happens if you have multiple graphical submit buttons in your form: <html><head>Multiple graphical submit buttons</head> <body> <form action="processor.php" method="post"> Enter part number: <input type="text" name="part"> <br> <input type="image" name="view" src="/images/view.gif"> <input type="image" name="edit" src="/images/edit.gif"> <input type="image" name="delete" src="/images/delete.gif"> <input type="image" name="order" src="/images/order.gif"> </form> </body> </html> Your PHP script would need to contain multiple branches, something like this: <?php if ($_POST['view_x']) { // code to view record } else if ($_POST['edit_x']) { // code to edit record } else if ($_POST['delete_x']) { // code to delete record } else if ($_POST['order_x']) { // code to place an order } ?>

Handling multiple forms

Handling multiple forms means the data of one form can be submitted to another form where that form holds the submitted data in hidden fields. In example we considered three form with names form1.php, form2.php and form3.php. Here form1 consists of a text field. It will be submitted to form2 using POST method . The submitted data can be given as value to hidden field as $name=$_POST[name]; <input type="hidden" name="name" value="<?php echo $name?>"/> Form2 consists of a combo box, now this form will be submitted to form3 where the combo box and hidden data will be placed in another two hidden fields in form3. The form3 will be submitted to submit.php page where the three forms data can be accessed there. FORM1.PHP <form method="post" action="form2.php"> Name<input type="text" name="name"/> <input type="submit" value="Submit" name="submit1"/> </form> FORM2.PHP <?php if(isset($_POST['submit1'])) { $name=$_POST['name']; ?> <form method="post" action="form3.php"> Select Country: <select name="country">

<option value="0">Select</option> <option value="ind">INDIA</option> <option value="us">USA</option> </select> <input type="hidden" name="name" value="<?php echo $name?>"/> <input type="submit" value="Submit" name="submit2"/> </form> <?php } else { echo "Please fill first form"; } ?> FORM3.PHP <?php if(isset($_POST['submit1'])) { $name=$_POST['name']; ?> <form method="post" action="form3.php"> Select Country: <select name="country">

<option value="0">Select</option> <option value="ind">INDIA</option> <option value="us">USA</option> </select> <input type="hidden" name="name" value="<?php echo $name?>"/> <input type="submit" value="Submit" name="submit2"/> </form> <?php } else { echo "Please fill first form"; } ?> SUBMIT.PHP <?php if(isset($_POST['submit3'])) { print_r($_POST); } ?> Output will be
Array ( [class] => 4 [name] => form1 [country] => ind [submit3] => Submit ) // with some example data

Preventing multiple PHP form submissions


When submitting a HTML form it can take several seconds before the form is successfully submitted and the response page shown. People can get inpatient and click the Submit button several times which can result in duplicate form submissions. Usually it's not really a problem, but in some cases you might want to prevent this from happening. Below you will find two simple tricks for preventing duplicate submissions, you can use either of these or a combination of both. prevent multiple form submissions using Javascript Using Javascript to block duplicate submissions is probably the easiest way. When someone submits the form we simply disable the Submit button and maybe change it's value to something more descriptive, like "Submitting, please wait..." Try clicking this button for example. It will remain disabled until you reload this page: The first step is to give your submit button a unique id, for example id="myButton":
<input type="submit" value="Submit" id="myButton" />

The second (and last) step is to give two Javascript commands to the <form> tag. The first one will tell the browser to disable the submit button after the form has been submitted and the second one will change the button text to give the user some idea about what's happening. This is the code to add to your form tag:
onsubmit="document.getElementById('myButton').disabled=true; document.getElementById('myButton').value='Submitting, please wait...';"

Your form tag would then look something like:


<form action="contact.php" method="post" onsubmit="document.getElementById('myButton').disabled=true; document.getElementById('myButton').value='Submitting, please wait...';" >

That's it. This trick should work in most modern browsers (IE 5+, FireFox, Opera, ...). prevent multiple form submissions using cookies If you wish to avoid duplicate submissions for the entire browser session (or longer) you can consider using cookies. For example edit your form processing script to send a cookie to the browser after the form has been processed but before any HTML or redirection headers are printed. Placing this code after the mail() command should work in most cases:

setcookie('FormSubmitted', '1');

Then check for the cookie before processing. If it's there this visitor already submitted the form in active browser session. Add this code to the beginning of your form processing script:
if (isset($_COOKIE['FormSubmitted']) { die('You may only submit this form once per session!'); }

Preventing multiple form submissions using SESSIONS

The problem of multiple form submissions is quite common in PHP. Many people use forms for database interactions and emailing etc, but when the form is submitted, the page can be refreshed and the POST data, or file uploads is POSTed once again. This tutorial brings an easy remedy to the issue with the use of form tokens and sessions. By setting a form token within a hidden field in the HTML form, the value can be checked in the page the form data is submitted to. The form token itself is simply a randomly generated string which is added to the form and stored in a session also. In this example the PHP function uniqid() is used to generate the form token value. The PHP part of the form.php page will look like this.
<?php /*** begin the session ***/ session_start(); /*** create the form token ***/ $form_token = uniqid(); /*** add the form token to the session ***/ $_SESSION['form_token'] = $form_token; ?>

The comments in the code describe the process acuratly, that a session is started, a unique form token is generated, and that value is added to the global PHP session array. The form token is again used in the HTML form in a hidden field, named form_token, otherwise, the form is just a standard HTML form. The completed form.php file will look like this.
<?php /*** begin the session ***/ session_start();

/*** create the form token ***/ $form_token = uniqid(); /*** add the form token to the session ***/ $_SESSION['form_token'] = $form_token; ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>My Form</title> </head> <body> <form action="submit.php" method="post"> <dl> <dt>Name</dt> <dd> <input type="hidden" name="form_token" value="<?php echo $form_token; ?>" /> <input type="text" name="first_name" /> </dd> </dl> <p><input type="submit" value="Add Name" /></p> </form> </body> </html>

The form action in the above file points to submit.php. This is the file that will process the form data. It could contain code to send emails, or code to perform some functions on a database. For the purposes of this tutorial, it is a simple process of saying thank you to the user and displaying the name.

You might also like