Saturday, 2 November 2013

Sanitize database inputs

Sanitize database inputs

When inserting data in your database, you have to be really careful about SQL injections and other attempts to insert malicious data into the db. The function below is probably the most complete and efficient way to sanitize a string before using it with your database.
function cleanInput($input) {

  $search = array(
    '@<script[^>]*?>.*?</script>@si', // Strip out javascript
    '@<[\/\!]*?[^<>]*?>@si',          // Strip out HTML tags
    '@<style[^>]*?>.*?</style>@siU',  // Strip style tags properly
    '@<![\s\S]*?--[ \t\n\r]*>@'       // Strip multi-line comments
  );

    $output = preg_replace($search, '', $input);
    return $output;
  }
?>
<?php
function sanitize($input) {
    if (is_array($input)) {
        foreach($input as $var=>$val) {
            $output[$var] = sanitize($val);
        }
    }
    else {
        if (get_magic_quotes_gpc()) {
            $input = stripslashes($input);
        }
        $input  = cleanInput($input);
        $output = mysql_real_escape_string($input);
    }
    return $output;
}
Here’s some examples of use:
<?php
  $bad_string = "Hi! 
<script src='http://www.evilsite.com/bad_script.js'></script>
 It's a good day!";
  $good_string = sanitize($bad_string);
  // $good_string returns "Hi! It\'s a good day!"

  // Also use for getting POST/GET variables
  $_POST = sanitize($_POST);
  $_GET  = sanitize($_GET);
?>

No comments:

Post a Comment