News & UpdatesProgrammingWeb programming StoreMy Projects
Links
Affiliates

PHP Tutorial – 14 – User Input

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 specified the script to which the form data is passed. For example, the following form submits one input property called myString to the script file MyPage.php.

<html>
<body>
  <form action="MyPage.php" method="post">
    <input type="text" name="myString" />
    <input type="submit" />
  </form>
</body>
</html>

The other required attribute of the form element specifies the sending method, which may be either get or post.

Sending with post

If the form is sent using the post method the data will be available through the $_POST array. The names of the properties will be the keys in that associative array. 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.

echo $_POST['myString'];

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.

echo $_GET['myString'];

Because the data is contained in the address bar this means that 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.

<a href="MyPage.php?myString=Foo+Bar">link</a>

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 file 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 and should therefore be validated and sanitized before being used. Validation means that you make sure 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 will be 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 to be output to the web page as text the htmlspecialchars function should be used. It will disable any HTML markup so 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 will be 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 in the example below.

<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 the following table.

NameDescription
nameOriginal name of uploaded file.
tmp_namePath to temporary server copy.
typeMime type of the file.
sizeFile size in bytes.
errorError code.

A received file is only temporarily stored on the server. If it is not saved by the script it will be deleted. A simple example of how to save the file is given below. 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 in order 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 the first argument contains a valid upload file, and if so it moves it to the path and renames it to the filename, 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 filename component of a path, including the file extension.

Superglobals

As seen in this chapter there are a number of built-in associate 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 a total of nine superglobals in PHP, each of which is described briefly below.

NameDescription
$GLOBALSContains all global variables, including other superglobals.
$_GETContains variables sent via a HTTP GET request.
$_POSTContains variables sent via a HTTP POST request.
$_FILESContains variables sent via a HTTP POST file upload.
$_COOKIEContains variables sent via HTTP cookies.
$_SESSIONContains variables stored in a user’s session.
$_REQUESTContains $_GET, $_POST and possibly $_COOKIE variables.
$_SERVERContains information about the web server and the request made to it.
$_ENVContains 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 will also display the general settings of the PHP configuration file, php.ini, along with other information regarding PHP.

phpinfo(); // display PHP information
Recommended additional reading:
Sams - Teach Yourself PHP in 24 Hours