如何阻止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 thrown as PDOExceptions.
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注入的实例文章,一步一步跟着作者脚步探索如何注入成功,展现了一次完整的渗透流程,值得一读.翻译水平有限,见谅! 一位客户让我们针对只有他们企业员工和顾客能使用的企业内网进行渗透测试. ...
随机推荐
- BootStrap基礎知識
BootStrap基礎知識 1. .lead //突出 .text-left //文字居左 .text-right //文字居右 .text-center //文字居中 .text-justify / ...
- CSV导出大量数据
$csvname = $csvname . '.csv'; header('Content-Type: application/vnd.ms-excel;charset=GB2312'); heade ...
- 【转】开源中国上看到的一个vim的自动配置的好东西,分享下
https://www.oschina.net/p/onekey-to-vim-ide 变量有高亮,竖行上有直线定位,对python的支持效果更佳,从事C/C++开发的程序员使用也不错.
- Split分割字符串
第一种方法:打开vs.net新建一个控制台项目.然后在Main()方法下输入下面的程序. string s="abcdeabcdeabcde"; string[] sArray=s ...
- vue组件初学--弹射小球
1. 定义每个弹射的小球组件( ocicle ) 2. 组件message自定义属性存放小球初始信息(可修改) { top: "0px", //小球距离上方坐标 left: &qu ...
- vscode 调试.net core 2.0 输出乱码解决方法
之前在vscode上调试.net core 2.0项目时输出窗口一直是乱码,查了很多资料无法解决 最终在github找到了解决办法 -> https://github.com/OmniSha ...
- 【转】HTTP Header 详解
HTTP(HyperTextTransferProtocol)即超文本传输协议,目前网页传输的的通用协议.HTTP协议采用了请求/响应模型,浏览器或其他客户端发出请求,服务器给与响应.就整个网络资源传 ...
- wxPython中基本控件学习
wxPython工具包提供了多种不同的窗口部件,包括了本章所提到的基本控件.我们涉及静态文本.可编辑的文本.按钮.微调.滑块.复选框.单选按钮.选择器.列表框.组合框和标尺.对于每种窗口部件,我们将提 ...
- slf4j+log4j在Java中实现日志记录
小Alan今天来跟大家聊聊开发中既简单又常用但必不可少的一样东西,那是什么呢?那就是日志记录,日志输出,日志保存. 后面就统一用日志记录四个字来形容啦. 日志记录是项目的开发中必不可少的一个环节,特别 ...
- 移动端分享到微信和QQ
关于在H5页面实现分享到微信和QQ,当初做的时候由于没有做过这方面的功能,也查了很多资料,找了很多插件,试了很多方法,大部分的都是点击后出现一个二维码,这不 符合我的需求,所以在网上找了一个 nati ...