AJAX请求中可能存在SQL注入


Possible SQL Injection in AJAX request?

我正在使用PHP和AJAX开发搜索索引,使其功能强大。当我使用burpsuit或其他安全扫描仪扫描它时,SQL注入出现在AJAX代码中,我找不到任何解决方案。代码如下:

<?php
require_once 'Connections/connect.php';
if($_GET['type'] == 'mobile'){
    $result = mysql_query("SELECT mobilep FROM dictionary where mobilep LIKE '".$_GET['name_startsWith']."%'"); 
    $data = array();
    while ($row = mysql_fetch_array($result)) {
        array_push($data, $row['mobilep']); 
    }   
    echo json_encode($data);
}

?>

这是非常糟糕的。。。您使用的是不推荐使用的mysql适配器。

http://php.net/manual/en/book.pdo.php

使用pdo和binds,这里有一个完整的原型:

class MySql
{
    private $sDbName      = '';
    private $sUsername    = '';
    private $sPassword    = '';
    private $sHost        = '';
    private $oConnection  = null;
    public function __construct()
    {
        $this->oConnection = new PDO( 
            'mysql:host=' 
            . $this->sHost 
            . ';dbname=' 
            . $this->sDbName, 
            $this->sUsername, 
            $this->sPassword 
            );
    }
    public function getDb()
    {
        return $this->oConnection;
    }
}
$aReturn[ 'data' ] = '';
if( !empty( $_GET[ 'type' ] )
    && ( !empty( $_GET[ 'name_startsWith' ] ) 
    && ( $_GET['type'] == 'mobile' ) 
    )
{
    $oMySql = new MySql;
    $oDb = $oMySql->getDb();
    $sSql = "SELECT mobilep FROM dictionary where mobilep LIKE :name";
    $aBinds[ ':name' ] = $_GET[ 'name_startsWith' ] . '%';
    $oStmp = $oDb->prepare( $sSql );
    $oMySql->bindVariables( $oStmp, $aBinds );
    $oStmp->execute();
    $oResults = $oStmp->fetchall();
    if( !empty( $oResults ) )
    {
        // var_dump( $aResults );
        $oErrors = $oStmp->errorInfo();
        // var_dump( $oErrors );
        $aReturn[ 'data' ] = $aResults;
    }
}
$sJson = json_encode( $aReturn, 1 );
header( 'Content-type', 'application/json' );
echo $sJson;

(是的,这是一个一年多前的问题。但没有选定的答案。我在搜索中遇到了这个问题…)

如果您一直使用mysql_接口函数,并且无法迁移到mysqli或PDO,那么最好使用mysql_real_sescape_string函数。

现有代码:

= mysql_query(" ... LIKE '". $_GET['name_startsWith'] ."%'");

要正确地转义潜在的不安全值,在将其合并到SQL文本中之前,请使用mysql_real_escape_string函数。。。

= mysql_query(" ... LIKE '". mysql_real_escape_string( $_GET['name_startsWith'] )."%'");
                             ^^^^^^^^^^^^^^^^^^^^^^^^^                          ^