How can I protect this code from SQL Injection? A bit confused

和自甴很熟 提交于 2019-12-24 02:05:05

问题


I've read various sources but I'm unsure how to implement them into my code. I was wondering if somebody could give me a quick hand with it? Once I've been shown how to do it once in my code I'll be able to pick it up I think! This is from an AJAX autocomplete I found on the net, although I saw something to do with it being vulnerable to SQL Injection due to the '%$queryString%' or something? Any help really appreciated!

if ( isset( $_POST['queryString'] ) )
{
  $queryString = $_POST['queryString'];
  if ( strlen( $queryString ) > 0 )
  {
    $query = "SELECT game_title, game_id FROM games WHERE game_title LIKE '%$queryString%' || alt LIKE '%$queryString%' LIMIT 10";
    $result = mysql_query( $query, $db ) or die( "There is an error in database please contact support@laglessfrag.com" );
    while ( $row = mysql_fetch_array( $result ) )
    {
      $game_id = $row['game_id'];
      echo '<li onClick="fill(\'' . $row['game_title'] . '\',' . $game_id . ');">' . $row['game_title'] . '</li>';
    }
  }
}

回答1:


The injection vulnerability is that you're passing user supplied data straight into a query without sanitizing it. In particular, this line is problematic:

$queryString = $_POST['queryString'];  

If you use the function mysql_real_escape_string() around $_POST['queryString'], that will prevent users from being able to insert their own code.

$queryString = mysql_real_escape_string($_POST['queryString']); 



回答2:


Use mysql_real_escape_string() on all values from untrusted sources before concatenating the value into the query string. (As a general rule, if you didn't hard code the value into the query string, escape it). For example:

$queryString = mysql_real_escape_string($_POST['queryString']);
$query =  "SELECT game_title, game_id "
        . "FROM games "
        . "WHERE game_title LIKE '%".$queryString."%'" 
        . "|| alt LIKE '%".$queryString."%' "
        . "LIMIT 10";

It is often easier to use a mysql adaptor that supports prepared statements which makes forgetting to sanitize input a lot harder. For example PHP has pdo or mysqli



来源:https://stackoverflow.com/questions/2555255/how-can-i-protect-this-code-from-sql-injection-a-bit-confused

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!