PHP PDO操作mysql不注意的话依然存在SQL注入
我们先来看一段代码
<?php
dbh = new PDO("mysql:host=localhost; dbname=demo", "user", "pass");
$dbh->exec("set names 'gbk'");
$sql="select * from test where name = ? and password = ?";
$stmt = $dbh->prepare($sql);
$exeres = $stmt->execute(array($name, $pass));
上面这段代码虽然使用了pdo的prepare方式来处理sql查询,但是当PHP版本<5.3.6之前还是存在宽字节SQL注入漏洞,原因在于这样的查询方式是使用了PHP本地模拟prepare,再把完整的SQL语句发送给MySQL服务器,并且有使用set names 'gbk'语句,所以会有PHP和MySQL编码不一致的原因导致SQL注入,正确的写法应该是使用ATTR_EMULATE_PREPARES 来禁用PHP本地模拟prepare,代码如下:
<?php
dbh = new PDO("mysql:host=localhost; dbname=demo", "user", "pass");
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->exec("set names 'utf8'");
$sql="select * from test where name = ? and password = ?";
$stmt = $dbh->prepare($sql);
$exeres = $stmt->execute(array($name, $pass));
<?php dbh = new PDO("mysql:host=localhost; dbname=demo", "user", "pass"); $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); $dbh->exec("set names 'utf8'"); $sql="select * from test where name = ? and password = ?"; $stmt = $dbh->prepare($sql); $exeres = $stmt->execute(array($name, $pass));