A PHP function to prevent SQL Injections and XSS

后端 未结 3 1761
暖寄归人
暖寄归人 2020-12-14 03:24

I am tring to make my PHP as secure as possible, and the two main things I am trying to avoid are

  • mySQL Injections
  • Cross-Side Scripting (XSS)
3条回答
  •  离开以前
    2020-12-14 03:54

    This function:

    function make_safe($variable) 
    {
       $variable = strip_tags(mysql_real_escape_string(trim($variable)));
       return $variable; 
    }
    

    Will not work

    SQL injection and XSS are two different beasts. Because they each require different escaping you need to use each escape function strip_tags and mysql_real_escape_string separatly.
    Joining them up will defeat the security of each.

    Use the standard mysql_real_escape_string() when inputting data into the database.
    Use strip_tags() when querying stuff out of the database before outputting them to the screen.

    Why combining the two function is dangerous
    From the horses mouth: http://php.net/manual/en/function.strip-tags.php

    Because strip_tags() does not actually validate the HTML, partial or broken tags can result in the removal of more text/data than expected.

    So by inputting malformed html into a database field a smart attacker can use your naive implementation to defeat mysql_real_escape_string() in your combo.

提交回复
热议问题