PHP Guide 3: Working with GET and POST Form data
A guide to getting and using GET and POST form data in PHP.
Index of Contents
With HTML there are two commonly used methods for passing data from one page to another. The first is the GET method, which is visible in the URL bar and appends the name/value data to the end of the URL. This data comes after a question mark (?) and each name/value pair is separated by an ampersand (&). This method is good when the user needs to be able to bookmark a page that has content generated by form data. The second method is POST, which stores the data as HTTP post data, and is not displayed in the URL bar. There are no size limitations to POST data, so it is prefered when passing data such as email or forum body text. It is also wise to use this method when passing sensitive data, as it won't be displayed in the URL bar.
Here is the PHP code used to retrieve form data.
// These two functions, &_GET and &_POST, are arrays that are automatically created and filled with
// the form data. Use brackets and your choice of single or double quotes with the name to retrieve
// the value of that form data, just like you would with an array.
// Here's a hypothetical web page URL with some GET form data:
// As you can see, "folder" contains the value 4 and "id" contains the value 236.
// Let's assign the value of these to variables so we can use them:
$folder = &_GET['folder'];
$id = &_GET['id'];
// That was easy, wasn't it?
// Since both $_GET and $_POST are arrays, we can use the print_r function to display everything they contain
// This is useful for testing purposes, especially with POST data as you cannot readily see it
// There is one more function that you will want to know, and it is the $_REQUEST function.
// This works the same as the two functions above except it contains the contents of both GET and POST data.
Real world example
In this example we will create a simple HTML web page with a form that submits POST data and then displays it.
if($_POST['name'] != '' && $_POST['age'] != '')
$name = $_POST['name'];
$age = $_POST['age'];
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="description" content="Form data">
<meta name="keywords" content="php, get, post, form, data">
<form action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<input type="submit" value="Submit">
// The isset function is used to check if a variable has been set
if(isset($name) && isset($age))
echo '<br>Hello ' . $name . ', you are ' . $age . ' years old!';