How do I prevent sql injection with php and mysql

前端 未结 4 1965
南旧
南旧 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:25

    You have to follow some rules while adding any data to the query, no matter from where it come - from user or form or anything. The rules always remain the same.

    To send a query to the database, you have 2 options:

    1. Build a query usual way, to make it look exactly as SQL query you can run in sql console.
      To do it, one should understand a whole set of rules, not just "use mysql_real_escape_string".
      Rules such as:

      • strings should be both enclosed in quotes and escaped. that's the only meaning of escaping: it's just easacpe delimiters! (and some other characters - string termination char and escape character itself). Without surrounding quotes mysql_real_escape_string is just useless.
      • numbers should be cast to it's type explicitly. Though while data numbers can be threaten just like strings, there are some numbers, like LIMIT clause parameters, which cannot be escaped and can be only cast.
    2. To send query and data separately.
      This is most preferred way as it can be shortened to just "use binding". All strings, numbers and LIMIT parameters can be bound - no worry at all.
      Using this method, your query with placeholders being sent to database as is, and bound data being sent in separate packets, so, it cannot interfere. It is just like code and data separation. You send your program (query itself) separated from the data.

    Everything said above covers only data insertion. But sometimes we have to make our query even more dynamic, adding operators or identifiers.
    In this case every dynamic parameter should be hardcoded in our script and chosen from that set.
    For example, to do dynamic ordering:

    $orders  = array("name","price","qty");
    $key     = array_search($_GET['sort'],$orders));
    $orderby = $orders[$key];
    $query   = "SELECT * FROM `table` ORDER BY $orderby";
    

    or dynamic search:

    $w     = array();
    $where = '';
    
    if (!empty($_GET['rooms']))     $w[]="rooms='".mesc($_GET['rooms'])."'";
    if (!empty($_GET['space']))     $w[]="space='".mesc($_GET['space'])."'";
    if (!empty($_GET['max_price'])) $w[]="price < '".mesc($_GET['max_price'])."'";
    
    if (count($w)) $where="WHERE ".implode(' AND ',$w);
    $query="select * from table $where";
    

    in this example we're adding to the query only data entered by user, not field names, which are all hardcoded in the script. For the binding the algorithm is very similar

    And so on.

提交回复
热议问题