PDO语句是否自动转义? [英] Are PDO statements automatically escaped?

查看:79
本文介绍了PDO语句是否自动转义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP PDO语句是自动转义的,还是仅准备好的语句?

Are PHP PDO statements automatically escaped, or only prepared statements?

例如,假设$username$password是用户输入.以下代码是否安全,或者容易被注入?

For example, assume that $username and $password are user inputs. Is the following code secure, or is it vulnerable to injection?

$dbh = new PDO("mysql:host=localhost;dbname=mydb", $my_mysql_username, $my_mysql_password);
$sth = $dbh->query("SELECT * FROM users WHERE username='$username' AND password='$password'");
$result = $sth->fetch();
if(!$result){
    $dbh->exec("INSERT INTO users (username, password) VALUES ('$username', '$password')");
}

(上面的代码纯粹是假设的,仅出于示例目的.)

如果没有自动转义它们,在这种情况下PDO是否对mysql_功能提供了额外的保护?

If they are not automatically escaped, does PDO provide any extra protection over the mysql_ functions in this situation?

推荐答案

假设您没有启用像魔术引号这样的丑陋功能,只有准备好的语句才能自动转义.准备语句时,仅对参数中的数据进行转义,而不对SQL字符串中已存在的任何内容进行转义.

Only prepared statements provide automagic escaping, assuming you don't have some ugliness like magic quotes enabled. And only the data in the params is escaped, not anything that's already in the SQL string when you prepare the statement.

如果要使用自动转义的好处,则必须准备一条语句并将其分别提供给数据.

If you want the benefits of auto escaping, you'll have to prepare a statement and feed it the data separately.

$sth = $dbh->prepare("SELECT * FROM users WHERE username=? AND password=?");
$sth->execute(array($username, $password));

否则,您对mysqli_query和朋友几乎没有保护. (我什至拒绝提及 mysql_query,因为不再有自尊的PHP程序员使用它了.哦,等等..该死.好吧,这是它唯一提到的地方.)

Otherwise, you get little to no protection over mysqli_query and friends. (I refuse to even mention mysql_query, because no self-respecting PHP programmer uses it anymore. Oh, wait..damn. Well, that's the only mention it gets here.)

这篇关于PDO语句是否自动转义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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