PHP DevCenter
oreilly.comSafari Books Online.Conferences.


PHP Foundations Working with Forms in PHP, Part 1

by John Coggeshall

In today's PHP Foundations, I'll begin my introduction of working with HTML forms from PHP. Since there is only time to discuss strictly PHP-related materials, I'll assume that you are already comfortable with HTML and creating HTML forms for user input. If you would like a refresher, there are a number of HTML resources available online. A personal favorite is Sizzling HTML.

Getting Form Data Into a PHP Script

Assuming that you have already designed a form to process with PHP, the first step is setting your form to submit its data to the PHP script. This is done via the <form> tag's action attribute. This attribute defines the URL to which the form submits its data. Set it to your PHP script. For instance, if your PHP processing script is called process.php, your <form> tag would resemble:

<form action="process.php" method="POST">

Also in PHP Foundations:

Using MySQL from PHP, Part 2

Using MySQL from PHP

MySQL Crash Course, Part 3

MySQL Crash Course, Part 2

MySQL Crash Course

When a form is submitted, the web server executes the PHP script and passes to it the values which were submitted in the submission. At this point, PHP automatically creates three "superglobal" arrays and populates them with the submitted data.

For those who have not been exposed to the term "superglobal," let me explain its meaning. The term refers to the scope in which a variable in PHP is normally available. For instance, an arbitrary variable $foobar may be defined outside of a function. It will not be available inside of the function unless the global statement is used. This is not the case with superglobal variables--they can be accessed from anywhere inside of a PHP script, regardless of the current scope, without using the global statement.

Which of these three superglobal arrays are used to store the data received from a form submission depends on the method by which the data was submitted. In the above <form> tag, the submission method was set to POST via the method attribute. Hence, PHP will store any data that is submitted in this form in the $_POST superglobal array. Likewise, if the GET method had been used then the $_GET superglobal array would contain the data.

Most of the time, it is good practice to write PHP scripts that look at only one method or another (whichever your form uses) when receiving input from the user. In certain circumstances it may not matter, so PHP also provides a third superglobal array, $_REQUEST, which contains all of the values from GET and POST submissions as well as any cookie variables that were passed, as well.

How are these three arrays structured based on the submission? All three superglobals are created as associative arrays whose key/value pairs represent the name of the given HTML element (specified by the name attribute) and the value of that element, respectively. Hence, the value from the following HTML input box:

<input type="TEXT" name="mytextbox" value="my value">

could be accessed by either $_GET['mytextbox'] or $_POST['mytextbox'], depending on the form submission method. Of course, the value can always be found in $_REQUEST['mytextbox'].

A Word About register_globals

In versions of PHP prior to 4.2.0, any variables that were sent from the client to the web server were automatically created as normal variables. (A text box named foo would have its value placed in the $foo variable.) This behavior could be turned on and off by adjusting the register_globals PHP directive in the php.ini file. In the post-version-4.2.0 world, this feature has been disabled by default because of security concerns. Although it is slightly less "clean" to use associative arrays instead of PHP variables, it is strongly recommended that this feature remain disabled for any script where security is a concern. A much better approach (without sacrificing security) is to use the import_request_variables() function. This function will create the same scalar variables as if register_globals were enabled, and has the following syntax:

import_request_variables($types [, $var_prefix])

$types represents which of the three types of variables to import (GET, POST, or cookie variables) by passing a string containing any combination of the characters G, P, and/or C representing GET, POST, and COOKIE values, respectively. The second parameter, $var_prefix, is an optional parameter representing a string with which to prefix the created variable names. The following code snippet will register all POSTed variables as scalar variables (each prefixed with mypost_ in the variable name):

import_request_variables("P", "mypost_");

/* Assuming $_POST['foo'] exists, the next line will 
   now print its value to the client browser */

 	echo $mypost_foo;

Importing Form Data as Arrays

As I have already illustrated, PHP will use the name of a form element as a key in the superglobal array to store its value. However, one thing that has not been covered at all is dealing with a form element in which more than one value is returned (for example, a list where multiple items can be selected). In such a case, you'll need to define your HTML form element names so that PHP can import the variables as an array.

In order for PHP to identify a particular variable name as containing an array, the name must include square brackets ([]) at the end of the value of its name attribute. This is illustrated in the following <select> form element:

<select name="mylist[]" multiple>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>

When the form containing this list is submitted, PHP will still register the key mylist in the appropriate superglobal ($_GET or $_POST). Instead of being a simple scalar value, however, mylist will be a zero-indexed array containing each element selected from the list.

This behavior is not limited to list HTML elements, but can be used for any information passed to the server by the client. Furthermore, the specific key for each element in the array can be specified. For instance, the following three input fields will all be stored under the mytext key of the relevant superglobal as an array containing the keys text1, text2, and text3:

<input type="TEXT" name="mytext[text1]">
<input type="TEXT" name="mytext[text2]">
<input type="TEXT" name="mytext[text3]">

Working with Checkboxes in PHP

Due to the nature of checkboxes, you may have already realized that checkboxes will not show up in PHP unless they have been checked. Dealing with this circumstance can be annoying (and perhaps insecure) unless properly dealt with. The first of these methods basically involves creating a hidden form element with the same name as the checkbox element and setting its value to zero, as shown below:

<input type="hidden" name="mycheckbox" value="0">
<input type="checkbox" name="mycheckbox" value="1">

The idea behind this solution is based on how PHP will respond if two elements (using the same method) have the same name. As was the case with the <select> element when in multi-select mode, PHP uses the last value provided to it. The hidden element will be used because the checkbox element is not sent to PHP if it is unchecked. Likewise, if the checkbox element is checked when the form is submitted, its value will override that of the hidden element.

Unfortunately, the drawback to this solution is a complete reliance on the browser to always send the hidden element before the checkbox element. Although it is logical to assume that elements will be sent in the same order as they are presented in the HTML document, there is no guarantee that this situation will be the case.

The second solution to this problem is much more eloquent for most situations. Unless you are unsure if a given checkbox was displayed to the user (if it may or may not be present in the form, depending the logic that created the form) create a boolean value based on the existence of the checkbox:

	/* Assume a checkbox by the name 'mycheckbox' exists */
	$checkbox = ($_GET['mycheckbox'] == 1);

The value of the $checkbox boolean will be set to true if the mycheckbox element exists (with the proper value), and false otherwise.

More on Forms Next Time

That's it for today's discussion of using forms in PHP. As you can see, in PHP, as long as you are aware of how PHP will respond, using user-submitted form data in your scripts is fairly simple. In my next article, I'll tackle the issue of uploading files from a HTML form using HTTP file uploads.

John Coggeshall is a a PHP consultant and author who started losing sleep over PHP around five years ago.

Read more PHP Foundations columns.

Return to the PHP DevCenter.

Valuable Online Certification Training

Online Certification for Your Career
Earn a Certificate for Professional Development from the University of Illinois Office of Continuing Education upon completion of each online certificate program.

PHP/SQL Programming Certificate — The PHP/SQL Programming Certificate series is comprised of four courses covering beginning to advanced PHP programming, beginning to advanced database programming using the SQL language, database theory, and integrated Web 2.0 programming using PHP and SQL on the Unix/Linux mySQL platform.

Enroll today!

Sponsored by: