"mysqli_real_escape_string"是否足以避免SQL注入或其他SQL攻击?

xRo*_*bot 4 php mysql security sql-injection

这是我的代码:

  $email= mysqli_real_escape_string($db_con,$_POST['email']);
  $psw= mysqli_real_escape_string($db_con,$_POST['psw']);

  $query = "INSERT INTO `users` (`email`,`psw`) VALUES ('".$email."','".$psw."')";
Run Code Online (Sandbox Code Playgroud)

有人可以告诉我它是否安全,或者它是否容易受到SQL注入攻击或其他SQL攻击?

Sco*_*ski 7

有人可以告诉我它是否安全,或者它是否容易受到SQL注入攻击或其他SQL攻击?

正如uri2x所说,请参阅SQL注入mysql_real_escape_string().

防止SQL注入的最佳方法是使用预准备语句.它们将数据(您的参数)与指令(SQL查询字符串)分开,并且不会为数据留下任何污染查询结构的空间.准备好的语句解决了应用程序安全性基本问题之一.

对于无法使用预准备语句的情况(例如LIMIT),为每个特定目的使用非常严格的白名单是保证安全性的唯一方法.

// This is a string literal whitelist
switch ($sortby) {
    case 'column_b':
    case 'col_c':
        // If it literally matches here, it's safe to use
        break;
    default:
        $sortby = 'rowid';
}

// Only numeric characters will pass through this part of the code thanks to type casting
$start = (int) $start;
$howmany = (int) $howmany;
if ($start < 0) {
    $start = 0;
}
if ($howmany < 1) {
    $howmany = 1;
}

// The actual query execution
$stmt = $db->prepare(
    "SELECT * FROM table WHERE col = ? ORDER BY {$sortby} ASC LIMIT {$start}, {$howmany}"
);
$stmt->execute(['value']);
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
Run Code Online (Sandbox Code Playgroud)

我认为上面的代码不受SQL注入的影响,即使在不起眼的边缘情况下也是如此.如果你正在使用MySQL,请确保你转动模拟准备.

$db->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);
Run Code Online (Sandbox Code Playgroud)

  • 答案是不”。我回答的第一句话是“看这个例子”,这证明这还不够。 (3认同)
  • @ScottArciszewski - 您给出的引用是关于“mysql_real_escape_string()”的答案,据我所知,它是与“mysqli_real_escape_string()”不同的函数。虽然你的建议还不错,但我认为这个答案并不正确。十多年来,我一直在使用使用“mysqli_real_escape_string()”转义的用户表单输入构建查询,尽管观察到了数千(数百万?)注入尝试,但没有一个成功。如果您认为它不安全,我想看一下演示。 (3认同)