sql注入攻击的概念及危害我相信大家都有所了解,如果不了解的请自己度娘,下面我们来学习一下在php中如何有效的防止
问题描述:
如果用户输入的数据在未经处理的情况下插入到一条sql查询语句,那么应用将很可能遭受到sql注入攻击,正如下面的例子:
$unsafe_variable = $_post['user_input'];
mysql_query(insert into `table` (`column`) values (' . $unsafe_variable . '));
因为用户的输入可能是这样的:
value'); drop table table;--
那么sql查询将变成如下:
insert into `table` (`column`) values('value'); drop table table;--')
应该采取哪些有效的方法来防止sql注入?
最佳回答(来自theo):
使用预处理语句和参数化查询。预处理语句和参数分别发送到数据库服务器进行解析,参数将会被当作普通字符处理。这种方式使得攻击者无法注入恶意的sql。 你有两种选择来实现该方法:
1、使用pdo:
$stmt = $pdo->prepare('select * from employees where name = :name');$stmt->execute(array('name' => $name));foreach ($stmt as $row) { // do something with $row}
2、使用mysqli:
$stmt = $dbconnection->prepare('select * from employees where name = ?');$stmt->bind_param('s', $name);$stmt->execute();$result = $stmt->get_result();while ($row = $result->fetch_assoc()) { // do something with $row}
pdo
注意,在默认情况使用pdo并没有让mysql数据库执行真正的预处理语句(原因见下文)。为了解决这个问题,你应该禁止pdo模拟预处理语句。一个正确使用pdo创建数据库连接的例子如下:
$dbconnection = new pdo('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8', 'user', 'pass');$dbconnection->setattribute(pdo::attr_emulate_prepares, false);$dbconnection->setattribute(pdo::attr_errmode, pdo::errmode_exception);
在上面的例子中,报错模式(attr_errmode)并不是必须的,但建议加上它。这样,当发生致命错误(fatal error)时,脚本就不会停止运行,而是给了程序员一个捕获pdoexceptions的机会,以便对错误进行妥善处理。 然而,第一个setattribute()调用是必须的,它禁止pdo模拟预处理语句,而使用真正的预处理语句,即有mysql执行预处理语句。这能确保语句和参数在发送给mysql之前没有被php处理过,这将使得攻击者无法注入恶意sql。了解原因,可参考这篇博文:pdo防注入原理分析以及使用pdo的注意事项。 注意在老版本的php(prepare('insert into table (column) values (:column)');$preparedstatement->execute(array('column' => $unsafevalue));