是"mysqli_real_escape_string"吗?足以避免SQL注入或其他SQL攻击? [英] Is "mysqli_real_escape_string" enough to avoid SQL injection or other SQL attacks?

查看:161
本文介绍了是"mysqli_real_escape_string"吗?足以避免SQL注入或其他SQL攻击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

  $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."')";

有人可以告诉我它是否安全或是否容易受到SQL Injection攻击或其他SQL攻击吗?

Could someone tell me if it is secure or if it is vulnerable to the SQL Injection attack or other SQL attacks ?

推荐答案

有人可以告诉我它是否安全或是否容易受到SQL Injection攻击或其他SQL攻击吗?

Could someone tell me if it is secure or if it is vulnerable to the SQL Injection attack or other SQL attacks ?

如uri2x所说,请参阅可绕过mysql_real_escape_string() 的SQL注入.

As uri2x says, see SQL injection that gets around mysql_real_escape_string().

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

The best way to prevent SQL injection is to use prepared statements. They separate the data (your parameters) from the instructions (the SQL query string) and doesn't leave any room for the data to contaminate the structure of your query. Prepared statements solve one of the fundamental problems of application security.

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

For situation where you cannot use prepared statements (e.g. LIMIT), using a very strict whitelist for each specific purpose is the only way to guarantee security.

// 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);

我认为即使在晦涩的情况下,以上代码也不受SQL注入的影响.如果您使用的是MySQL,请确保关闭模拟准备.

I posit that the above code is immune to SQL injection, even in obscure edge cases. If you're using MySQL, make sure you turn emulated prepares off.

$db->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);

这篇关于是"mysqli_real_escape_string"吗?足以避免SQL注入或其他SQL攻击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆