PHP Sanitize Form Data
On the Web, Cross-Site Scripting (XSS) is one of the most common types of attacks. Fortunately, there is an easy fix: always filter input data and always escape output data.
Example of vulnerable form data
Consider the following form:
<form action="form.php" method="post">
<textarea name="comment"></textarea>
<input type="submit" value="submit">
</form>
After the form is submitted, let’s say that the comment
data is displayed like so:
echo $_POST['comment'];
This scenario introduces vulnerability because the input is not filtered and the output is not escaped. So if a user submits the following JavaScript code:
<script>alert('You are hacked.');</script>
..when the comment is displayed in the page, visitors will get a popup dialog box in their face that says, “You are hacked.” Not good. Let’s see how to prevent this scenario from happening.
How to sanitize form data
To keep form data secure, first it is important to always filter or validate all input data. There are many ways to do this, but the easiest to strip all tags, like so:
$clean_comment = strip_tags($_POST['comment']);
Using PHP’s strip_tags() to sanitize the form data means that all HTML and PHP tags will be removed. Thus, the <script>
tags used in the previous example will not be included in the posted comment, so no malicious script may be executed.
Likewise, before displaying the form data, it is important to always escape it, like so:
$clean_comment = htmlentities($clean_comment, ENT_QUOTES, 'UTF-8');
Here we are using PHP’s htmlentities() to convert all applicable characters to their HTML character entity equivalents. This means, for example, that single quotes will be converted to HTML entities, so that the malicious code used in the previous example will not trigger a popup alert.
Of course, there are numerous other sanitization techniques that will work depending on context and your own personal security strategy. If in doubt, do some research and arrive at your own conclusions.
Take-home message: always filter input and escape output to secure your form data.