PHP PDO操作mysql不注意的话依然存在SQL注入
最近出了一本书叫做《代码审计:企业级web代码安全架构》,专门介绍怎么从代码里挖掘漏洞,漏洞应该怎么防御,功能应该怎么设计会更安全。 需要的朋友可以在淘宝、京东等网站搜索。
我们先来看一段代码
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,代码如下:
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));

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
