Filter Input in PHP

Aug 21, 2009 Author: SQLmaster

Since all input is tainted and cannot be trusted, it is necessary to filter your input to ensure that input received is input expected. To do this, use a whitelist approach, as described earlier. As an example, consider the following HTML form:

form method="POST">Username: 
<input type="text" name="username" />
<br />Password: 
<input type="text" name="password" />
<br />Favourite colour:
<select name="colour">
</select><br /><input type="submit" />

This form contains three input elements: username, password, and colour. For this example, username should contain only alphabetic characters, password should contain only alphanumeric characters, and colour should contain any of “Red,” “Blue,” “Yellow,” or “Green.” It is possible to implement some client-side validation code using JavaScript to enforce these rules, but, as described later in the section on spoofed forms, it is not always possible to force users to use only your form and, thus, your client-side rules. Therefore, server-side filtering is important for security, while client-side validation is important for usability. To filter the input received with this form, start by initializing a blank array. It is important to use a name that sets this array apart as containing only filtered data; this example uses the name $clean. Later in your code, when encountering the variable $clean[’username’], you can be certain that this value has been filtered. If, however, you see $_POST[’username’] used, you cannot be certain that the data is trustworthy. Thus, discard the variable and use the one from the $clean array instead. The following code example shows one way to filter the input for this form:

$clean = array();
if (ctype_alpha($_POST[’username’]))
$clean[’username’] = $_POST[’username’];
if (ctype_alnum($_POST[’password’]))
$clean[’password’] = $_POST[’password’];
$colours = array(’Red’, ’Blue’, ’Yellow’, ’Green’);
if (in_array($_POST[’colour’], $colours))
$clean[’colour’] = $_POST[’colour’];

Filtering with a whitelist approach places the control firmly in your hands and ensures that your application will not receive bad data. If, for example, someone tries to pass a username or colour that is not allowed to the processing script, the worst than can happen is that the $clean array will not contain a value for username or colour. If username is required, then simply display an error message to the user and ask them to provide correct data. You should force the user to provide correct information rather than trying to clean and sanitize it on your own. If you attempt to sanitize the data, you may end up with bad data, and you’ll run into the same problems that result with the use of blacklists.

tags: Filter Input

views 4091
  1. Add New Comment