Sanitizing User Input with PHP

If you don’t already know, not sanitizing user input in your scripts is very bad.  It can lead to XSS attacks which I won’t get into here, there is plenty of info out there.  It is especially bad if you are saving the user input into databases as a evil hacker could end up deleting everything you’ve got.  I don’t pretend to be a security expert but the following code is what I use to clean any input from the user.  I use this whether I am creating a contact form and just emailing the data off or if I’m inserting some information into a database.  If you see anything wrong, please let me know so I can adjust it.

function clean_input($data) {
    $return = array();
    foreach ($data as $key => $value) {
        if (is_array($value)) {
            foreach ($value as $key2 => $value2) {
                if (get_magic_quotes_gpc()) {
                    $value2 = stripslashes($value2);
                }
                if (!is_numeric($value2)) {
                    $value2 = mysql_escape_string($value2);
                }
                $return[$key][$key2] = $value2;
            }
        } else {
            if (get_magic_quotes_gpc()) {
                $value = stripslashes($value);
            }
            if (!is_numeric($value)) {
                $value = mysql_escape_string($value);
            }
            $return[$key] = $value;
         }
    }
    return $return;
}

To use the function you can call

$clean = clean_input($_POST); // or $_GET

Then you can use $clean['whatever'] in your code.

A couple notes:

  • I am not using mysql_real_escape_string, the updated version of the php function.  I can’t assume that you’ve opened a database connection before calling the function.  This wouldn’t be needed for things such as contact forms on a static site.  If you have a database connection open, I’d change the mysql_escape_string to mysql_real_escape string.
  • This doesn’t do any checks for proper type and format of any input, you’ll have to do that on your own next.

It can handle two dimension arrays so if for example you have a multiple select box, it will correctly cycle through each value.  Hope this helps you out there.

Leave a Reply