Class 8 – Passing Data With Forms
Posted: November 6th, 2009 | Author: amos | Filed under: php, xhtml | Tags: class 8 | 1 Comment »Understanding how to use the $_GET, $_POST, and $_REQUEST variables is critical to creating a site in PHP. So here is an in-depth analysis of how data is passed from one page to another using forms.
In our earlier post, we discussed the concept of persistent data. Each web page is like a distinct application that does not share any information with any other web page. But sometimes, you want one script to communicate with another script. Sometimes two different pages need to share data.
In this post, we’re going to take a look at three things:
- an XHTML form in which a user will enter some data
- the HTTP request, which is the technical mechanism the browser uses to send the data the user entered in the form to the server
- the way a PHP script can access the data the user entered in the form and do something with it
The example scenario
As an example, let’s say we have created a website where users can sign up to receive a free guide to Sri Lankan real estate in the mail. So there is a form that the user has to fill out where they enter their shipping address. When the user clicks the “submit” button on that form, that data that they entered is taken from the page on which they entered it, and is sent to another script using either a GET or POST request to the server.
These two types of HTTP requests, GET and POST, are the primary ways that a browser can make requests pages from a server. (For an overview of all possible types of requests and responses between web clients and servers, you can look up the HTTP reference page on Wikipedia).
index.php, the XHTML file
Let’s imagine that index.php is the XHTML code for the form where the user enters his shipping information. This form just has a bunch of text fields that a user fills in with his shipping address. Then the user clicks “Send it now!” to submit the form:
<form action="process_signup.php" method="POST"> <label for="full_name">Name:</label> <input type="text" id="full_name" name="full_name" /> <br /> <label for="street">Street:</label> <input type="text" id="street" name="street" /> <br /> <label for="city">City:</label> <input type="text" id="city" name="city" /> <br /> <label for="state">State:</label> <input type="text" id="state" name="state" /> <br /> <label for="zip">Zip:</label> <input type="text" id="zip" name="zip" /> <br /> <input type="submit" value="Send it now!" /> </form>
When viewed in the browser, and surrounded by the usual <html>, <head>, and <body> tags, this page, without any style sheets, will look something like this:
The HTTP POST request
When the form is “submitted”, what this means in technical terms is that the browser actually makes an HTTP POST request to the server for the file, process_payment.php. We can tell this because the <form> tag has two attributes: “action” and “method”, which indicate what the browser should do when the user clicks the submit button.
<form action="process_payment.php" method="POST">
The “action” attribute indicates which page the browser should request when the user clicks submit. The “method” attribute indicates which HTTP type of request the browser should make. In this case it’s a POST request.
The POST request asks the server for the process_signup.php file, but along with that request it also sends the data the user entered in the form to the server. That data is sent in a way that is invisible to the user, hidden in the HTTP headers that the browser uses to make the formal request the server for the process_payment.php file.
If we were to somehow intercept those invisible headers that the browser sends as its formal request to the server, they would look something like this:
POST /process_signup.php HTTP/1.1 Host: www.mysite.com User-Agent: Mozilla/4.0 Content-Length: 27 Content-Type: application/x-www-form-urlencoded full_name=Amos+Bloomberg&street=145+4th+Avenue&city=New+York&state=NY&zip=10003
The top part are the generic HTTP POST headers indicating what file the browser wants, and what kind of client the browser is. The bottom line contains the urlencoded data that the user entered in the form. This is how POST method submits data to the server. But you’ll never see any of that since it is never shown to the user.
Notice that the data in the bottom line holds the data that the user entered as a series of key=value pairs, with a very specific syntax:
key1=value1&key2=value2&key3=value3 ... and so on...
In urlencoding, all key/value pairs are separated by ampersands, “&”. The key to each piece of data from a form is always the “name” attribute of the XHTML form field in which the user entered the data. The value is always the text that the user entered.
So “full_name” is what we put in the “name” attribute of the first <input> tag in the form…
<input type="text" id="full_name" name="full_name" />
..so that’s the term that is used as the key to that piece of data in the HTTP POST request that is sent to the server.
full_name=Amos+Bloomberg&street=145+4th+Avenue&city=New+York&state=NY&zip=10003
“street” is what we used as the “name” attribute of the second <input> tag in the XHTML, so that’s what is used as the key to the second piece of data in the HTTP POST request. And so on for all the other form fields.
process_signup.php, the PHP script
Once that form has been submitted and the HTTP POST request has been made to the server, the server sees that the file that the browser requested is a PHP script, so it runs that script on the server before sending anything back to the client.
PHP, since it is built specifically for the web, is smart enough to know that the PHP code in the scripts on the server might be interested in the details of the data that was sent along with the HTTP request, meaning the data that the user entered in the form. So PHP provides a few special variables that contain that data in an easy-to-use format.
The $_POST variable is built-in associative array that automatically is set to hold all of the data that was sent along with in any HTTP POST request to the server. The index of each element in the associative array is the same word that was used as the key in the key=value pair that represented that data in the HTTP request. This is also, if you recall, always the same word as the “name” attribute of the form field in which the user entered the data.
So in our example, the $_POST array will have 5 elements. If we were to dump out the raw data stored in the $_POST array in our PHP script using the built-in print_r() function, which we always use to debug arrays, it would look something like this:
Array( full_name => Amos Bloomberg, street => 145 4th Avenue, city => New York, state => NY, zip => 10003 )
We can access each element in the array individually in PHP by using the $_POST array with the correct term as the index, using the syntax $_POST['<index name>']. For example:
$fullName = $_POST['full_name']; $street = $_POST['street']; $city = $_POST['city']; $state = $_POST['state']; $zip = $_POST['zip'];
The important thing is that the index that we use each time we access the $_POST array is the same word that we used in the “name” attribute of the form field <input> tag in the XHTML page where the user entered their address.
Assuming all the names we use as indexes for the $_POST array in the PHP match the “name” attributes of all the form fields the user filled in on the XHTML page, we will have successfully passed data from one page to another. Data the user entered from the form has been passed to the PHP script.
Assuming the XHTML “names” and the PHP indexes match, we will now have the data that the user entered in the form stored in our variables, $fullName, $street, $city, $state, and $zip. And we can do whatever we want with that information, for example storing it in a database, or sending it in an email to someone.
The HTTP GET request
As an alternative, we could have used the HTTP GET method instead of the POST method when submitting the form. To do this, we would have changed the form tag in the XHTML to be:
<form action="process_payment.php" method="GET">
The practical difference between the two is that with GET, the data that the user enters in the form is attached to the URL of the file that the client is requesting from the server. And users will see the data they entered in the form show up in the address bar of the browser, when it requests the file process_signup.php, so data passed along with a GET request is not invisible or hidden from the user.
If we were to intercept the headers in an HTTP GET request to the server, it would look something like this:
GET /process_signup.php?full_name=Amos+Bloomberg&street=145+4th+Avenue&city=New+York&state=NY&zip=10003 Host: www.mysite.com User-Agent: Mozilla/4.0
Notice how the data the user entered in the form is tacked on to the end of the file name that the browser is requesting from the server. The user will see all this data in the browser address bar as well.
Just as the data sent along with the POST request to the server in our original example was automatically stored in a $_POST variable in the PHP script on the server, process_signup.php, the data sent along with the GET request is automatically stored in a $_GET variable. And you can access that data in almost the exact same way you did with the $_POST variable in your PHP code:
$fullName = $_GET['full_name']; $street = $_GET['street']; $city = $_GET['city']; $state = $_GET['state']; $zip = $_GET['zip'];
So, as I hope is obvious, the $_GET variable only holds data that was passed to a PHP script via the GET method. And the $_POST variable holds only that data that was passed to the server via a POST request. Do not try to mix and mingle the two.
The $_REQUEST variable
Whereas the $_GET variable only holds data passed to the server with an HTTP GET request, and the $_POST variable only holds data passed to the server in an HTTP POST request, the $_REQUEST variable holds any data passed to the server along with either type of request. It also holds data passed via cookies.
The $_REQUEST variable is a sort-of catch-all for any data passed to the server, regardless of how it got there. So regardless of whether the form used the method POST or the method GET, we could use this code in the PHP script to access the data:
$fullName = $_REQUEST['full_name']; $street = $_REQUEST['street']; $city = $_REQUEST['city']; $state = $_REQUEST['state']; $zip = $_REQUEST['zip'];
As you can see, the built-in $_REQUEST variable is an associative array with indexes that are the same words we used in the “name” attribute of each field in the XHTML form, just as $_POST and $_GET were.

hosting
Wypatrujesz nietrudnego i lukratywnego sposobu, ażeby podwyższyć profity prywatnej firmy? Mam zatem dla Ciebie genialne wyjście. Reklama. Rozumiem, miało być tanio, ale zapewniam Cię, iż tak będzie. Najłatwiejszą i najbardziej całościową, jednakże jednocześnie w największym stopniu funkcjonalną formą reklamy jest strona WWW. W tej chwili, jeśliby Twojej jednostki biznesowej nie ma w Necie to możesz zapomnieć o rozległych przychodach. Każdy wypatruje przede wszystkim w sieci światowej, wówczas w następnej kolejności opcjonalnie sięga po ogłoszenia w gazecie, czy podpytuje kolegów. Zajrzyjmy prawdzie w oczy, strona jest w zasadzie potrzebna. O ile nie jesteś wytrawny w sytuacjach domen i Internetu nie martw się. Nasza jednostka zaistniała skutkiem tego szczególnie dla Ciebie. Zaświadczamy usługi z odcinka hosting od startu do mety. Nasi eksperci odpowiedzą na Twoje wszelakie spytania i pomogą wybrać najbardziej optymalną propozycję dla Ciebie. Dzięki nam zdołasz podnieść zyski swojej jednostki biznesowej przy naprawdę nikłym nakładzie pieniężnym. Jakim sposobem? Na skutek usługi hosting. Przedstawisz się tutaj z skończoną ofertą na hosting i znajdziesz dane do kontaktu z nami. Przetestuj w jaki sposób Sieć zdoła Cię wesprzeć.