PSD to HTML conversion PSD to HTML conversion PSD2HTML.com with over 300 professionals takes the designs to HTML and beyond

Code Snippet

Home » Code Snippets » PHP » Sanitize Database Inputs

Sanitize Database Inputs

1) Function for stripping out malicious bits

<?php
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;
  }
?>

2) Sanitization function

Uses the function above, as well as adds slashes as to not screw up database functions.

<?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;
}
?>

Usage

<?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);
?>

Reference URL

Subscribe to The Thread

  1. I use my own functions as follow:

    function text_global($poster) {
      $poster = stripslashes($poster);
      $poster = str_replace(Array("\n", "'", "‘", "’", "′", "“", "”", "„", "″", '"'), Array("", "’", "’", "’", "’", """, """, """, """, """), $poster);
        return $poster;
    }
    
    while (list($Key, $Val) = each($_POST)) {
     if (substr($Key, 0, 4) != "fsk_") {
      if (is_array($Val) === true) {
       while (list($sKey, $sVal) = each($Val)) {
        $Val[$sKey] = text_global($sVal);
       }
       $_POST[$Key] = $Val;
      } else {
       $_POST[$Key] = text_global($Val);
      }
     }
    }

    Where “fsk_” prefix is used for WYSIWYG editor variables. Works perfectly.

    • @iMaxEst: I think you may have missed the point here. Preparing data is just a side issue. Sanitizing data prevents code injection attacks.

      stripslashes() != sanitize()

  2. Really nice functions Chris! Neat way using regular Expressions these snippets will definetly find there way to my library script.

    Thanks a bunch!

  3. Why to clean the input from html/script tags?
    You only have to worry about XSS when you prepare the output!

    Protect your database through prepared statements and htmlspecialchars() will care about the output.

  4. It seems like a good idea to clean input. Why do I want to store potentially malignant code in my database?

  5. What about ASP ? anyone..

  6. These code snippets don’t come through very nicely via RSS. All the line breaks seem to disappear.

  7. amm257

    These are nigh useless and overly complicated; e.g. the html one simply matches anything with “<", so why not make that explicit? Currently that's all that expression does, all this extra stuff merely serves to obfuscate the issue. E.g. the javascript one doesn't work, all I have to do is add a space: "scripthere”, the browser will figure out what I meant, and the script will execute.

    • amm257

      I apologize, whoever wrote this filter did it both right and wrong (wrong because they simply remove it, instead of escaping it, right because it catches it), I’ve cleaned it up with characters escaped by hand, this should work:

      These are nigh useless and overly complicated; e.g. the html one simply matches anything with “<”, so why not make that explicit? Currently that’s all that expression does, all this extra stuff merely serves to obfuscate the issue. E.g. the javascript one doesn’t work, all I have to do is add a space: “< script>scripthere</script>”, the browser will figure out what I meant, and the script will execute.

  8. Mines is pretty small and handy for getting rid of nasty hacking injections

    function clean($text)
    {
    	$text = strip_tags($text);
    	$text = htmlspecialchars($text, ENT_QUOTES);
    
        return ($text); //output clean text
    }
  9. Dyllon

    mine simply strips out the brackets.

    function clean($code)
    {
        $strip = array(
            '<' => '&lt;',
            '>' => '&gt;'
        );
    
        return strtr($code, $strip);
    }
  10. Hi,

    We are looking for a consultant who could evaluate our website and check how vulnerable we are to these kind of malicious scripts.

    Any recommendation?

    Thanks,

    Mark

    • Don’t know a consultant but I am reading “pro PHP security – from application security principles to the implementation of XSS defenses” which explains this stuff quite well

    • Mark, dunno if you’re still interested, but I’ve had several years of this line of work. There are several other areas of attacks that I can investigate for you as well. Simply contact me at http://www.matatechconsulting.com/contact/ for more details.

  11. Chris, why use your regexes instead of PHP’s strip_tags(), as suggested by gibigbig? I don’t understand what functionality is added by going that route.

  12. Glad I found. I was just thinking about this yesterday and needed a better fn.

    Is the filter_var() fn any good? ie. filter_var($value, FILTER_SANITIZE_STRING)

  13. Thanks for the tutorial, this is very useful

  14. The safest way is to parameterise inputs by using classes such as PDO since PHP is a loosely typed language.

    Or simply cast the inputs into the type that you would expect, e.g. Expect an integer? Just put (int) before the input. Type casting is the fastest operation to sanitize numbers.

  15. Andriah

    Hi! It’s a good day!

    I’m just testing how this works?

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~