本篇文章给大家带来了关于php的相关知识,其中主要跟大家聊一聊什么是预处理语句?php的预处理查询是如何防止sql注入的?感兴趣的朋友下面一起来看一下吧,希望对大家有帮助。
php的预处理查询是如何防止sql注入的?
目前最有效的防止 sql 注入的方式使用预处理语句和参数化查询。
以最常用的 php pdo 扩展为例。
官方文档中对预处理语句的介绍
什么是预处理语句?
可以把它看作是想要运行的 sql 的一种编译过的模板,它可以使用变量参数进行定制。
预处理语句的两大好处:
1;查询仅需解析(或预处理)一次,但可以用相同或不同的参数执行多次。当查询准备好后,数据库将分析、编译和优化执行该查询的计划。对于复杂的查询,此过程要花费较长的时间,如果需要以不同参数多次重复相同的查询,那么该过程将大大降低应用程序的速度。通过使用预处理语句,可以避免重复分析 / 编译 / 优化周期。简言之,预处理语句占用更少的资源,因而运行得更快。
2.提供给预处理语句的参数不需要用引号括起来,驱动程序会自动处理。如果应用程序只使用预处理语句,可以确保不会发生 sql 注入。(然而,如果查询的其他部分是由未转义的输入来构建的,则仍存在 sql 注入的风险)。
pdo 的特性在于驱动程序不支持预处理的时候,pdo 将模拟处理,此时的预处理-参数化查询过程在 pdo 的模拟器中完成。pdo 模拟器根据 dsn 中指定的字符集对输入参数进行本地转义,然后拼接成完整的 sql 语句,发送给 mysql 服务端。
所以,pdo 模拟器能否正确的转义输入参数,是拦截 sql 注入的关键。
小于 5.3.6 的 php 版本,dsn (data source name) 是默认忽略 charset 参数的。这时如果使用 pdo 的本地转义,仍然可能导致 sql 注入。
因此,像 laravel 框架底层会直接设置 pdo::attr_emulate_prepares=false,来确保 sql 语句和参数值在被发送到 mysql 服务器之前不会被 php 解析。
php 的实现
// 查询$calories = 150;$colour = 'red'; $sth = $dbh->prepare('select name, colour, calories from fruit where calories < :calories and colour = :colour'); $sth->bindvalue(':calories', $calories, pdo::param_int); $sth->bindvalue(':colour', $colour, pdo::param_str); $sth->execute();
// 插入,修改,删除$preparedstmt = $db->prepare('insert into table (column) values (:column)');$preparedstmt->execute(array(':column' => $unsafevalue));
laravel 的底层实现
// 查询的实现public function select($query, $bindings = [], $usereadpdo = true){ return $this->run($query, $bindings, function ($query, $bindings) use ($usereadpdo) { if ($this->pretending()) { return []; } $statement = $this->prepared( $this->getpdoforselect($usereadpdo)->prepare($query) ); $this->bindvalues($statement, $this->preparebindings($bindings)); $statement->execute(); return $statement->fetchall(); });}// 修改删除的实现public function affectingstatement($query, $bindings = []){ return $this->run($query, $bindings, function ($query, $bindings) { if ($this->pretending()) { return 0; } $statement = $this->getpdo()->prepare($query); $this->bindvalues($statement, $this->preparebindings($bindings)); $statement->execute(); $this->recordshavebeenmodified( ($count = $statement->rowcount()) > 0 ); return $count; });}
推荐学习:《php视频教程》
以上就是一文解析php的预处理查询怎么防止sql注入的详细内容。