string() a good defense against SQL Injection?

This question already has an answer here:

  • Can I protect against SQL Injection by escaping single-quote and surrounding user input with single-quotes? 18 answers
  • How can I prevent SQL injection in PHP? 28 answers
  • SQL injection that gets around mysql_real_escape_string() 4 answers

  • NO

    is_string() will not protect against SQL injection, a numeric payload will not be able to cause any table damage or unwanted access regardless, and string sanitization does not protect against all SQL injection.

    I should give you the spiel about why prepared statements are amazing and all that, but you yourself indicated that the point of the question was to point out flaws in sanitization

    Why You Should Use Prepared Statements Over Sanitization

  • There are situations where you want unsanitized data in your database, eg specially formatted text (like LaTeX, XML, or JSON), where you would need to de-sanitize data, which is not a 100% guarantee of accuracy (eg XML file which includes HTML entities like " would be changed to ", changing the data)
  • Prepared statements can be re-bound and executed in very few lines
  • Theoretically, if you have a query like the one below, sanitization will not save you(borrowed from here)

    $iId = mysql_real_escape_string("1 OR 1=1");
    $sSql = "SELECT * FROM table WHERE id = $iId";


  • NO: PHP delusion #1: Mysql(i)_real_escape_string prevents SQL injection

    This filter, will thwart any malicious user inputs like haha' , inj''

    Your ideas are anything but a protection. There is nothing "malicious" in user inputs like haha' , inj'', neither a really malicious input would contain any of these characters.

    That said, any user input is a string, so you will create a mockery of the notorious magic quotes feature, much despised and long removed from the language.

    Go for the prepared statements.

    链接地址: http://www.djcxy.com/p/93456.html

    上一篇: SQL查询参数化如何工作?

    下一篇: string()可以很好地防御SQL注入?