简体   繁体   English

如何从SQL注入中保护此代码? 有点困惑

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

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? 这是我在网上找到的一个AJAX自动完成,虽然我看到由于'%$ queryString%'或其他原因它容易受到SQL注入的影响? 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>';
    }
  }
}

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. 如果你在$_POST['queryString']周围使用函数mysql_real_escape_string() ,那将阻止用户插入自己的代码。

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

Use mysql_real_escape_string() on all values from untrusted sources before concatenating the value into the query string. 在将值连接到查询字符串之前,对来自不受信任的源的所有值使用mysql_real_escape_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. 使用支持预处理语句的mysql适配器通常更容易,这使得忘记清理输入更加困难。 For example PHP has pdo or mysqli 例如,PHP有pdomysqli

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM