如何阻止sql注入(pdo篇)
Use prepared statements and parameterized queries. These are SQL statements that are sent to and parsed by the database server separately from any parameters. This way it is impossible for an attacker to inject malicious SQL.
You basically have two options to achieve this:
Using PDO (for any supported database driver):
$stmt = $pdo->prepare('SELECT * FROM employees WHERE name = :name'); $stmt->execute(array('name' => $name)); foreach ($stmt as $row) {
// do something with $row
}Using MySQLi (for MySQL):
$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
}
If you're connecting to a database other than MySQL, there is a driver-specific second option that you can refer to (e.g. pg_prepare()
and pg_execute()
for PostgreSQL). PDO is the universal option.
Correctly setting up the connection
Note that when using PDO
to access a MySQL database real prepared statements are not used by default. To fix this you have to disable the emulation of prepared statements. An example of creating a connection using PDO is:
$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);
In the above example the error mode isn't strictly necessary, but it is advised to add it. This way the script will not stop with a Fatal Error
when something goes wrong. And it gives the developer the chance to catch
any error(s) which are throw
n as PDOException
s.
What is mandatory however is the first setAttribute()
line, which tells PDO to disable emulated prepared statements and use real prepared statements. This makes sure the statement and the values aren't parsed by PHP before sending it to the MySQL server (giving a possible attacker no chance to inject malicious SQL).
Although you can set the charset
in the options of the constructor, it's important to note that 'older' versions of PHP (< 5.3.6) silently ignored the charset parameter in the DSN.
Explanation
What happens is that the SQL statement you pass to prepare
is parsed and compiled by the database server. By specifying parameters (either a ?
or a named parameter like :name
in the example above) you tell the database engine where you want to filter on. Then when you call execute
, the prepared statement is combined with the parameter values you specify.
The important thing here is that the parameter values are combined with the compiled statement, not an SQL string. SQL injection works by tricking the script into including malicious strings when it creates SQL to send to the database. So by sending the actual SQL separately from the parameters, you limit the risk of ending up with something you didn't intend. Any parameters you send when using a prepared statement will just be treated as strings (although the database engine may do some optimization so parameters may end up as numbers too, of course). In the example above, if the $name
variable contains 'Sarah'; DELETE FROM employees
the result would simply be a search for the string "'Sarah'; DELETE FROM employees"
, and you will not end up with an empty table.
Another benefit with using prepared statements is that if you execute the same statement many times in the same session it will only be parsed and compiled once, giving you some speed gains.
Oh, and since you asked about how to do it for an insert, here's an example (using PDO):
$preparedStatement = $db->prepare('INSERT INTO table (column) VALUES (:column)');
$preparedStatement->execute(array('column' => $unsafeValue));
Can Prepared Statements Be Used For Dynamic Queries?
While you can still use prepared statements for the query parameters, the structure of the dynamic query itself cannot be parametrized and certain query features (e.g. LIMIT $start, $number
) cannot be parametrized.
For example, this will not work:
$stmt = $pdo->prepare('SELECT * FROM employees ORDER BY name ASC LIMIT ?, ?'); // Bad query
$stmt->execute(array(0, 30));
For these specific scenarios, the best thing to do is use a whitelist filter that restricts the possible values or the possible characters.
// Value whitelist
// $dir can only be 'DESC' or 'ASC'
$dir = !empty($direction) ? 'DESC' : 'ASC';
// Character set whitelist
// $offset will never contain a non-numeric character
$offset = preg_replace('/[^0-9]+/', '', $offset);
if (empty($offset)) {
$offset = 0;
}
// Explicit data types
// $number will always be an integer. We use a binary AND operation
// ($number & PHP_INT_MAX) to prevent integer overflows from creating
// invalid characters from alternative notation.
$number = (int) ($number < 0 ? 1 : ($number & PHP_INT_MAX));
$stmt = $pdo->prepare(
'SELECT * FROM employees ORDER BY name '.$dir.' LIMIT '.$offset.', '.$number
如何阻止sql注入(pdo篇)的更多相关文章
- 管中窥豹——框架下的SQL注入 Java篇
管中窥豹--框架下的SQL注入 Java篇 背景 SQL注入漏洞应该算是很有年代感的漏洞了,但是现在依然活跃在各大漏洞榜单中,究其原因还是数据和代码的问题. SQL 语句在DBMS系统中作为表达式被解 ...
- egg 阻止 sql 注入,相关文章
egg 阻止 sql 注入,相关文章 网址 注意!!我们极其不建议开发者拼接 sql 语句,这样很容易引起 sql 注入!!如果必须要自己拼接 sql 语句,请使用 mysql.escape 方法. ...
- SQL注入漏洞篇
一篇SQL注入漏洞汇总,更新中-- 如有缺陷 望大佬指正 SQL注入产生的原因? 当程序执行逻辑时没有对用户输入的参数做过滤处理,使参数直接与后台数据库产生逻辑交互,即SQL注入黑客就可以利用各种SQ ...
- urlScan 配置阻止sql注入
工具 urlscan_v31_x64 urlscan_v31_x86 URLScan是一个IIS下的ISAPI 筛选器,它能够限制服务器将要处理的HTTP请求的类型.通过阻止特定的 HTTP 请求,U ...
- SQL注入总结篇
分类SQL注入的攻击方式根据应用程序处理数据库返回内容的不同,可以分为可显注入.报错注入和盲注. 可显注入攻击者可以直接在当前界面内容中获取想要获得的内容. 报错注入数据库查询返回结果并没有在页面中显 ...
- 【荐】PDO防 SQL注入攻击 原理分析 以及 使用PDO的注意事项
我们都知道,只要合理正确使用PDO,可以基本上防止SQL注入的产生,本文主要回答以下几个问题: 为什么要使用PDO而不是mysql_connect? 为何PDO能防注入? 使用PDO防注入的时候应该特 ...
- SQL注入(一) - 入门篇
什么是SQL注入 可能大家还不是对SQL注入这个概念不是很清楚,简单地说,SQL注入就是攻击者通过正常的WEB页面,把自己SQL代码传入到应用程序中,从而通过执行非程序员预期的SQL代码,达到窃取数据 ...
- PDO防 SQL注入攻击 原理分析 以及 使用PDO的注意事项
我们都知道,只要合理正确使用PDO(PDO一是PHP数据对象(PHP Data Object)的缩写),可以基本上防止SQL注入的产生,本文主要回答以下几个问题: 为什么要使用PDO而不是mysql_ ...
- 实例讲解 SQL 注入攻击
这是一篇讲解SQL注入的实例文章,一步一步跟着作者脚步探索如何注入成功,展现了一次完整的渗透流程,值得一读.翻译水平有限,见谅! 一位客户让我们针对只有他们企业员工和顾客能使用的企业内网进行渗透测试. ...
随机推荐
- ②jquery复习
# jQuery 复习--by 传智前端与移动开发学院 ## 1. jQuery是什么?(了解)+ www.github.com+ jQuery 其实就是一堆的js函数,是普通的js,只不过应用广泛, ...
- Highway Networks Pytorch
导读 本文讨论了深层神经网络训练困难的原因以及如何使用Highway Networks去解决深层神经网络训练的困难,并且在pytorch上实现了Highway Networks. 一 .Highway ...
- Android Studio 导入应用时报错 Error:java.lang.RuntimeException: Some file crunching failed, see logs for details
在app文件夹的build.gradle里加上 android { ...... aaptOptions.cruncherEnabled = false aaptOptions.useNewCrunc ...
- 不要62 hdu2089
不要62 Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submis ...
- C# 7 局部函数剖析
局部函数是C# 7中的一个新功能,允许在一个函数中定义另一个函数. 何时使用局部函数? 局部函数的主要功能与匿名方法非常相似:在某些情况下,创建一个命名函数在读者的认知负担方面代价太大.有时,函数本身 ...
- windows下PHP中Fatal error Call to undefined function curl_init()的解决方法
参考官方解决方法:http://nz.php.net/manual/en/curl.installation.php 1.php安装目录下的ext文件夹下面是否有php_curl.dll文件,然后右键 ...
- Go语言备忘录:反射的原理与使用详解
目录: 预备知识 reflect.Typeof.reflect.ValueOf Value.Type 动态调用 通过反射可以修改原对象 实现类似“泛型”的功能 1.预备知识: Go的变量都是静态类 ...
- Python面试题之python是一种什么语言及优缺点
1.说说python是一种什么语言? 参考答案:python是一门动态解释性的强类型定义语言 编译型vs解释型 编译型优点:编译器一般会有预编译的过程对代码进行优化.因为编译只做一次,运行时不需要编译 ...
- 在SQLSERVER中创建DBLINK,操作远程服务器数据库
--配置SQLSERVER数据库的DBLINK exec sp_addlinkedserver @server='WAS_SMS',@srvproduct='',@provider='SQLOLEDB ...
- Echarts数据可视化全解注释
全栈工程师开发手册 (作者:栾鹏) Echarts数据可视化开发代码注释全解 Echarts数据可视化开发参数配置全解 6大公共组件详解(点击进入): title详解. tooltip详解.toolb ...