问题
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