When an HTML form is submitted to a PHP page, the data becomes available to that script.
HTML Form
An
HTML form has two required attributes:
action and
method. The action attribute specifies the script file to which the form data is passed when the form is submitted. For example, the following form submits one input property called
myString to the
mypage.php script file.
<?php // myform.php ?>
<!doctype html>
<html>
<body>
<form action="mypage.php" method="post">
<input type="text" name="myString">
<input type="submit">
</form>
</body>
</html>
The second required attribute of the form element specifies the sending method, which may be either GET or POST.
Sending with POST
When this form is submitted, the browser loads mypage.php and passes the form data along. If the form is sent using the
POST method, the data becomes available to the receiving script through the
$_POST array. The names of the form input properties become keys in that associative array.
<?php // mypage.php ?>
<!doctype html>
<html>
<body>
<?php echo $_POST['myString']; ?>
</body>
</html>
Data sent with the POST method is not visible on the URL of the page, but this also means that the state of the page cannot be saved by, for example, bookmarking the page.
Sending with GET
The alternative to POST is to send the form data with the
GET method and to retrieve it using the
$_GET array. The variables are then displayed in the address bar, which effectively maintains the state of the page if it is bookmarked and revisited.
// mypage.php
echo $_GET['myString'];
Because the data is contained in the address bar, variables cannot only be passed through HTML forms but also through HTML links. The
$_GET array can then be used to change the state of the page accordingly. This provides one way of passing variables from one page to another, as seen in the following example.
<?php // sender.php ?>
<!doctype html>
<html>
<body>
<a href="receiver.php?myString=Foo+Bar">link</a>
</body>
</html>
When the
link on this web page is clicked, the receiver.php file can access the data that has been passed to it. The following example displays the data on the page.
<?php // receiver.php ?>
<!doctype html>
<html>
<body>
<?php echo $_GET['myString']; // "Foo Bar" ?>
</body>
</html>
Request Array
If it does not matter whether the POST or GET method was used to send the data, the
$_REQUEST array
can be used. This array typically contains the
$_GET and
$_POST arrays, but may also contain the
$_COOKIE array.
echo $_REQUEST['myString']; // "Foo Bar"
The content of the $_REQUEST array can be set in the PHP configuration file1 and varies between PHP distributions. Due to security concerns, the $_COOKIE array is usually not included.
Security Concerns
Any user-provided data can be manipulated; therefore, it should be validated and sanitized before being used.
Validation
means that you make sure that the data is in the form you expect, in terms of data type, range, and content. For example, the following code validates an email address.
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
echo "Invalid email address";
Sanitizing
is when you disable potentially malicious code in the user input. This is done by escaping the code according to the rules of the language where the input is to be used. For example, if the data is sent to a database, it needs to be sanitized with the
mysql_real_escape_string function to disable any embedded SQL code.
// Sanitize for database use
$name = mysql_real_escape_string($_POST['name']);
// Execute SQL command
$sql = "SELECT * FROM users WHERE user='" . $name . "'";
$result = mysql_query($sql);
When user-supplied data is output to the web page as text, the
htmlspecialchars function should be used. It disables any HTML markup, so that the user input is displayed but not interpreted.
// Sanitize for web page use
echo htmlspecialchars($_POST['comment']);
Submitting Arrays
Form data can be grouped into arrays by including
array square brackets after the variable names in the form. This works for all form input elements, including
<input>,
<select>, and
<textarea>.
<input type="text" name="myArr[]">
<input type="text" name="myArr[]">
The elements may also be assigned their own array keys.
<input type="text" name="myArr[name]">
Once submitted, the array is available for use in the script.
$val1 = $_POST['myArr'][0];
$val2 = $_POST['myArr'][1];
$name = $_POST['myArr']['name'];
The form
<select> element has an attribute for allowing multiple items to be selected from the list.
<select name="myArr[]" size="3" multiple="true">
<option value="apple">Apple</option>
<option value="orange">Orange</option>
<option value="pear">Pear</option>
</select>
When this multi-select element is included in a form, the array brackets become necessary for retrieving the selected values in the script.
foreach ($_POST['myArr'] as $item)
echo $item . ' '; // ex "apple orange pear"
File Uploading
The HTML form provides a file input type that allows files to be uploaded to the server. For
file uploading to work, the form’s optional
enctype attribute must be set to
"multipart/form-data", as shown in the following example.
<form action="mypage.php" method="post"
enctype="multipart/form-data">
<input name="myfile" type="file">
<input type="submit" value="Upload">
</form>
Information about the uploaded file is stored in the
$_FILES array. The keys of this associative array are seen in Table
23-1.
Table 23-1Keys of the $_FILES Array
Name | Description |
---|
name | Original name of uploaded file. |
tmp_name | Path to temporary server copy. |
type | Mime type of the file. |
size | File size in bytes. |
error | Error code. |
A received file is only temporarily stored on the server. If it is not saved by the script, it will be deleted. The following shows a simple example of how to save the file. The example checks the error code to make sure that the file was successfully received and, if so, moves the file out of the temporary folder to save it. In practice, you would also want to examine the file size and type to determine whether the file is to be
kept.
$dest = 'upload/' . basename($_FILES['myfile']['name']);
$file = $_FILES['myfile']['tmp_name'];
$err = $_FILES['myfile']['error'];
if($err == 0 && move_uploaded_file($file, $dest))
echo 'File successfully uploaded';
Two new functions are seen in this example. The move_uploaded_file function checks to ensure that the first argument contains a valid upload file, and if so, it moves it to the path and renames it to the file name specified by the second argument. The specified folder must already exist, and if the function succeeds in moving the file, it returns true. The other new function is basename. It returns the file name component of a path, including the file extension.
Superglobals
As seen in this chapter, there are a number of built-in associative arrays that make external data available to PHP scripts. These arrays are known as
superglobals
, because they are automatically available in every scope. There are nine superglobals in PHP, each of which is described briefly in Table
23-2.
Name | Description |
---|
$GLOBALS | Contains all global variables, including other superglobals. |
$_GET | Contains variables sent via an HTTP GET request. |
$_POST | Contains variables sent via an HTTP POST request. |
$_FILES | Contains variables sent via an HTTP POST file upload. |
$_COOKIE | Contains variables sent via HTTP cookies. |
$_SESSION | Contains variables stored in a user’s session. |
$_REQUEST | Contains $_GET, $_POST, and possibly $_COOKIE variables. |
$_SERVER | Contains information about the web server and the request made to it. |
$_ENV | Contains all environment variables set by the web server. |
The content of the variables
$_GET,
$_POST,
$_COOKIE,
$_SERVER, and
$_ENV is included in the output generated by the
phpinfo function. This function also displays the general settings of the PHP configuration file,
php.ini, along with other information regarding PHP.
phpinfo(); // display PHP information