带有转义字符串的SQL注入?

时间:2014-11-03 19:45:19

标签: php mysql sql-injection code-injection

我目前正在使用这个PHP代码进行身份验证,我想知道它是否容易受到MySQL注入攻击。特别是如果某人可以使用UNION或其他攻击返回虚假数据,从而伪造登录。我目前正在使用mysqli_real_escape_string来尝试防止琐碎的攻击,并尝试清理请求。但是,由于使用了mysqli_real_escape_string,这段代码是否完全安全,还是存在安全漏洞?

$email = mysqli_real_escape_string($database_connection, $_POST["email"]);
$pass = mysqli_real_escape_string($database_connection, $_POST["pass"]);
$query = "SELECT * FROM auths WHERE email='$email' AND pass='$pass'";
$query_result = mysqli_query($database_connection, $query);

if(mysqli_num_rows($query_result) === 1) 
{
    // User is logged in.
}
else
{
    die("Unauthorized");
}

1 个答案:

答案 0 :(得分:3)

忘记mysqli_real_escape_string。只需使用prepared statements

即可
$conn = new mysqli('host', 'user', 'pass', 'database');        
$stmt = $conn->prepare('select * from auths where email=? and pass=?');
$stmt->bind_param('ss', $_POST['email'], $_POST['pass']);
$stmt->execute();
if($stmt->num_rows > 0):
    //user is logged in
else:
    die('Unauthorized');
endif;