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:

  1. 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
    }
  2. 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篇)的更多相关文章

  1. 管中窥豹——框架下的SQL注入 Java篇

    管中窥豹--框架下的SQL注入 Java篇 背景 SQL注入漏洞应该算是很有年代感的漏洞了,但是现在依然活跃在各大漏洞榜单中,究其原因还是数据和代码的问题. SQL 语句在DBMS系统中作为表达式被解 ...

  2. egg 阻止 sql 注入,相关文章

    egg 阻止 sql 注入,相关文章 网址 注意!!我们极其不建议开发者拼接 sql 语句,这样很容易引起 sql 注入!!如果必须要自己拼接 sql 语句,请使用 mysql.escape 方法. ...

  3. SQL注入漏洞篇

    一篇SQL注入漏洞汇总,更新中-- 如有缺陷 望大佬指正 SQL注入产生的原因? 当程序执行逻辑时没有对用户输入的参数做过滤处理,使参数直接与后台数据库产生逻辑交互,即SQL注入黑客就可以利用各种SQ ...

  4. urlScan 配置阻止sql注入

    工具 urlscan_v31_x64 urlscan_v31_x86 URLScan是一个IIS下的ISAPI 筛选器,它能够限制服务器将要处理的HTTP请求的类型.通过阻止特定的 HTTP 请求,U ...

  5. SQL注入总结篇

    分类SQL注入的攻击方式根据应用程序处理数据库返回内容的不同,可以分为可显注入.报错注入和盲注. 可显注入攻击者可以直接在当前界面内容中获取想要获得的内容. 报错注入数据库查询返回结果并没有在页面中显 ...

  6. 【荐】PDO防 SQL注入攻击 原理分析 以及 使用PDO的注意事项

    我们都知道,只要合理正确使用PDO,可以基本上防止SQL注入的产生,本文主要回答以下几个问题: 为什么要使用PDO而不是mysql_connect? 为何PDO能防注入? 使用PDO防注入的时候应该特 ...

  7. SQL注入(一) - 入门篇

    什么是SQL注入 可能大家还不是对SQL注入这个概念不是很清楚,简单地说,SQL注入就是攻击者通过正常的WEB页面,把自己SQL代码传入到应用程序中,从而通过执行非程序员预期的SQL代码,达到窃取数据 ...

  8. PDO防 SQL注入攻击 原理分析 以及 使用PDO的注意事项

    我们都知道,只要合理正确使用PDO(PDO一是PHP数据对象(PHP Data Object)的缩写),可以基本上防止SQL注入的产生,本文主要回答以下几个问题: 为什么要使用PDO而不是mysql_ ...

  9. 实例讲解 SQL 注入攻击

    这是一篇讲解SQL注入的实例文章,一步一步跟着作者脚步探索如何注入成功,展现了一次完整的渗透流程,值得一读.翻译水平有限,见谅! 一位客户让我们针对只有他们企业员工和顾客能使用的企业内网进行渗透测试. ...

随机推荐

  1. 《MATLAB从入门到放弃》二维曲线和图形绘制基础(二):使用Help文档学习line、plot、plotyy、subplot、hold绘图函数

    目录: »  plot 最常用的二维曲线绘图函数 >  帮助文档 >  基本使用语法 >  线条的样式.符号和颜色调整 >  图形属性调整 >  使用图形句柄进行设置 » ...

  2. C - Coin Change (III)(多重背包 二进制优化)

    C - Coin Change (III) Time Limit:2000MS     Memory Limit:32768KB     64bit IO Format:%lld & %llu ...

  3. ES中const

      前  言 EScript 上一次总结了,ES中let和var的区别,今天在带大家了解另一个声明关键词:const. const实际上保证的,并不是变量的值不得改动,而是变量指向的那个内存地址不得改 ...

  4. 用MXNet实现mnist的生成对抗网络(GAN)

    用MXNet实现mnist的生成对抗网络(GAN) 生成式对抗网络(Generative Adversarial Network,简称GAN)由一个生成网络与一个判别网络组成.生成网络从潜在空间(la ...

  5. C-图文上边对齐

    1.效果 1.1 样式设置 2 效果  2.1 样式

  6. 远程连接MySQL,防火墙阻止访问,解决方法

    远程连接MySQL,防火墙阻止访问,解决方法   xp/2003添加防火墙例外端口 打开防火墙,选择例外选项卡,添加端口 名称:mysqlport 端口号:3306 选中TCP win7添加防火墙例外 ...

  7. Django 模型中自定义Manager和模型方法

    1.自定义管理器(Manager) 在语句Book.objects.all()中,objects是一个特殊的属性,通过它来查询数据库,它就是模型的一个Manager. 每个Django模型至少有一个m ...

  8. 多个code.csdn.net账号切换

    code.csdn.net是国内开源库 使用git需要在项目添加密钥 而如果有多个账户,一个是私人,一个是公司,那么这时怎么做? 密钥存在~/.ssh默认是id_rsa 那么一个比较笨的办法是做一个k ...

  9. win10 uwp 隐藏实时可视化

    新的vs有个功能,实时可视化 但是他会挡我们界面,想要隐藏 点击转到实时可视化,就是点击横线看到,接着就可以看到下面的选项 点击在应用程序中显示运行时,就是不选中 很简单就看到,没有那个 本作品采用知 ...

  10. Developing Universal Windows Apps 开发UWA应用 问答

    开始是一些欢迎,就不翻译 Question: Is the code already there? Answer: There is some code on that codeplex site, ...