It can never be emphasized enough that handling user data is a security minefield, and that it is essential to learn to treat all such data with the utmost caution. The first thing to remember is that regardless of what constraints you have placed in an HTML form to limit the types and sizes of inputs, it is a trivial matter for a hacker to use her browser’s view source feature to extract the form and modify it to provide malicious input to your website.
Instead of just using code such as the following when reading in user input:
$variable = $_POST['user_input'];
You should also use one or more of the following lines of code.
- to prevent escape characters being injected into a string that will be presented to MySQL:
$variable = mysql_real_escape_string($variable);
- to get rid of unwanted slashes:
$variable = stripslashes($variable);
- to remove any HTML from a string:
$variable = htmlentities($variable);
- to strip HTML entirely from an input:
$variable = strip_tags($variable);
Here are two helpful functions to sanitize your PHP code:
<?php
function sanitizeString($var) {
if (get_magic_quotes_gpc()) $var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}
function sanitizeMySQL($var) {
$var = mysql_real_escape_string($var);
$var = sanitizeString($var);
return $var;
}