为什么这个 SQL 代码不安全? [英] Why is this SQL code insecure?

查看:51
本文介绍了为什么这个 SQL 代码不安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚让我的一个朋友查看了一些我用来从我的数据库中获取数据的代码,他告诉我它非常不安全,而且 SQL 注入是严重的问题.

I just had a friend of mine look over some code I'm using to get data from my database, and he tells me it's very unsecure and that SQL injection is serious shit.

这是我现在使用的代码:

Here's the code I'm using now:

$id = $_GET['id'];
$result = mysql_query("SELECT * FROM news WHERE id = $id") or die("err0r");

他告诉我解决方案是将该代码更改为:

He tells me that the solution is to change that code into:

$id = intval($_GET['id']);
$result = mysql_query("SELECT * FROM news WHERE id = $id") or die("err0r");

我的代码以某种方式(根据我朋友的说法)使任何用户都能够编辑我数据库中的内容:

My code somehow (according to my friend) makes any user able to edit content in my database:

http://mydomain.com/?p=news&id=38;DROP TABLE tablename;

有人能准确解释一下他的意思吗?

Could someone explain exactly what he means?

谢谢您,祝您有个愉快的一天

Thank you and have a pleasant day

推荐答案

考虑如果有人发布 http://www.mydomain.com?id=1; 会发生什么;DROP TABLE 新闻

旧版本的 PHP 试图通过自动转义所有输入变量来自动防止此类事情;即通过向输入中的任何引号字符添加斜杠,以便它们不会破坏 SQL 查询.这不再是当前 PHP 版本的默认设置,因为它会导致许多其他问题.

Older versions of PHP tried to automatically protect against this sort of thing by automatically escaping all the input variables; ie by adding slashes to any quote characters in the input so that they wouldn't break a SQL query. This is no longer the default in current versions of PHP since it caused a lot of other issues.

但是,在您的情况下,您甚至没有在 SQL 查询中引用变量,因此即使这种保护也无济于事,因为黑客不需要包含任何引号来攻击您.

However in your case, you haven't even quoted the variable in the SQL query, so even that protection wouldn't have helped you since a hacker wouldn't have needed to include any quotes to hack you.

intval() 解决方案确实会在这种特定情况下为您提供帮助,但在其他情况下则无济于事(例如,如果您需要处理字符串变量).

The intval() solution will indeed help you in this specific case, but it won't help in others (eg if you need to handle a string variable).

正确的解决方法:

  1. 您应该对所有要传递到 SQL 查询的变量使用 mysql_real_escape_string() 函数,以防止任何可能的黑客攻击,如下所示:

  1. You should use the mysql_real_escape_string() function on all variables that are to be passed into the SQL query to prevent any possible hack attacks, like so:

$escaped_id = mysql_real_escape_string($id);

  • 您应该将 SQL 字符串中的所有变量括在引号中,如下所示:

  • You should enclose all variables in the SQL string in quotes, like this:

    $result = mysql_query("SELECT * FROM news WHERE id = '$escaped_id'");
    

  • 顺便说一句...这个漫画是一个非常受欢迎的链接来演示问题.;-)

    By the way... This comic strip is a very popular thing to link to to demonstrate the problem. ;-)

    这篇关于为什么这个 SQL 代码不安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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