How do I prevent sql injection with php and mysql

前端 未结 4 1963
南旧
南旧 2020-12-20 06:42

I have a form into which the visitor can enter data, and I want to store this data in a mysql database via the $_POST variable. What do I need to prevent sql injection?

4条回答
  •  一向
    一向 (楼主)
    2020-12-20 07:23

    I gave a presentation at the PHP TEK-X conference in May 2010 about this topic, and I tried to cover multiple methods for defending against SQL Injection. There is no single method that is best in all cases, so you should learn multiple methods and use all of them:

    • Validate user input or any other content from external sources (even data from within your own database) before interpolating it into an SQL query. You can use PHP's filter extension or regular expressions, for instance.

    • Force external content to be in correct format. For example, (int) $_POST["userid"] typecasts that content to be a plain integer, so it's safe to use.

    • When including dynamic content in place of literal values in SQL expressions, use prepared queries with parameters. Note that the plain mysql extension in PHP does not support query parameters -- use PDO. I don't use mysqli because its API is inconsistent and hard to use.

    • When using the IN() predicate, you can't use one parameter for a list of values. Concatenate multiple parameter placeholders, as many as you have values in your list. This is not hard, it only take a line or two of code:

      $sql = "SELECT ... FROM ... WHERE user_id IN ("
          . join(",", array_fill(0,count($userid_list),"?")) . ")";
      $pdoStmt = $pdo->prepare($sql);
      $pdoStmt->execute($userid_list);
      
    • When using dynamic table names, column names, or SQL keywords, you can't use query parameters. You have to interpolate dynamic content. But you can use whitelisting techniques to map the untrusted content to legal, safe identifiers and keywords.

    See my presentation SQL Injection Myths and Fallacies for more information and examples.

    Also you might like my new book SQL Antipatterns: Avoiding the Pitfalls of Database Programming. My book has a chapter about SQL Injection.

提交回复
热议问题