简体   繁体   English

使用PDO在MySQL中清理输入的正确方法

[英]Correct way to sanitize input in MySQL using PDO

so I had a friend of mine try to run a SQLinjection on my site and he managed to get into it using the code underneath. 所以我有一个朋友尝试在我的网站上运行SQLinjection,他设法使用下面的代码进入它。 How can I prevent this? 我怎么能阻止这个? I have read something about sanitizing the variables but how do I do this? 我已经阅读了有关清理变量的内容,但我该怎么做?

';INSERT INTO login (username, password) VALUES ('Gjertsmells', 'password');SELECT 'password' FROM Login WHERE 'x'='x '; INSERT INTO登录(用户名,密码)VALUES('Gjertsmells','密码'); SELECT'密码'FROM登录WHERE'x'='x

$db = new PDO('mysql:host=XXXXXXXX;dbname=XXXXXXX', 'XXXXXXXXXX', 'XXXXXXXXX');

        // query MySQL to verify login
        $query = $db->prepare("SELECT password FROM login WHERE username='$username'");
        $query->execute();

        $column = $query->fetchColumn();
        if($column === $password)

The idea of prepared statements is that you don't concatenate variables, instead you bind the parameters. 准备语句的想法是你不连接变量,而是绑定参数。 The difference is the variable never gets inserted into the SQL, rather the MySQL engine handles the variable separately which leaves no possibility of SQL Injection. 区别在于变量永远不会插入到SQL中,而是MySQL引擎单独处理变量,这样就不会出现SQL注入。 This also has the added bonus that no escaping or pre-processing of the variable is required. 这还有额外的好处,即不需要对变量进行转义或预处理。

$query = $db->prepare("SELECT password FROM login WHERE username = :username");
$query->execute(array(':username' => $username));

Prepare your statement like this: 准备你的声明如下:

$query = $db->prepare("SELECT `password` FROM `login` WHERE `username` = :username");
$query->execute(array(":username" => $username));

Or bind the parameters using the same prepared statement like this: 或者使用相同的预准备语句绑定参数,如下所示:

$query->bindParam(":username", $username, PDO::PARAM_STR);

$query->execute();

This way you shouldn't have to sanitize your query. 这样您就不必清理查询。

Don't sanitize input. 不要消毒输入。 Just make sure that you really write to the database what ever data is provided (ie protect against SQL injection) and then escape your output. 只需确保您真正写入数据库提供的数据(即防止SQL注入),然后转义输出。

To protect against SQL injection, use bound parameters . 要防止SQL注入,请使用绑定参数 To escape your output, use htmlspecialchars on web pages and any other encoding appropriate given the medium you are outputting to. 要转义输出,请在网页上使用htmlspecialchars ,并根据输出的介质使用任何其他适当的编码。

Just remember that you have to do both of the above. 请记住,你必须做到以上两点。 If you only protect against SQL injection attacks, you'll still leave your site wide open to XSS attacks. 如果您只是防止SQL注入攻击,您仍然会使您的站点对XSS攻击敞开大门。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM