产生原因

一方面自己没这方面的意识,有些数据没有经过严格的验证,然后直接拼接 SQL 去查询。导致漏洞产生,比如:

$id  = $_GET['id'];
$sql = "SELECT name FROM users WHERE id = $id";

因为没有对 $_GET['id'] 做数据类型验证,注入者可提交任何类型的数据,比如 " and 1= 1 or " 等不安全的数据。如果按照下面方式写,就安全一些。

$id  = intval($_GET['id']);
$sql = "SELECT name FROM users WHERE id = $id";

把 id 转换成 int 类型,就可以去掉不安全的东西。

验证数据

防止注入的第一步就是验证数据,可以根据相应类型进行严格的验证。比如 int 类型直接同过 intval 进行转换就行:

$id =intval( $_GET['id']);

字符处理起来比较复杂些,首先通过 sprintf 函数格式话输出,确保它是一个字符串。然后通过一些安全函数去掉一些不合法的字符,比如:

$str = addslashes(sprintf("%s",$str)); 
//也可以用 mysqli_real_escape_string 函数替代addslashes

这样处理以后会比较安全。当然还可以进一步去判断字符串长度,去防止「缓冲区溢出攻击」比如:

$str = addslashes(sprintf("%s",$str)); 
$str = substr($str,0,40); //最大长度为40

参数化绑定

参数化绑定,防止 SQL 注入的又一道屏障。php MySQLi 和 PDO 均提供这样的功能。比如 MySQLi 可以这样去查询:

$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
$stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)");
$code = 'DEU';
$language = 'Bavarian';
$official = "F";
$percent = 11.2;
$stmt->bind_param('sssd', $code, $language, $official, $percent);

PDO 的更是方便,比如:

/* Execute a prepared statement by passing an array of values */
$sql = 'SELECT name, colour, calories
FROM fruit
WHERE calories < :calories AND colour = :colour'; $sth = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
$sth->execute(array(':calories' => 150, ':colour' => 'red'));
$red = $sth->fetchAll();
$sth->execute(array(':calories' => 175, ':colour' => 'yellow'));
$yellow = $sth->fetchAll();

我们多数使用 php 的框架进行编程,所以最好不要自己拼写 SQL,按照框架给定参数绑定进行查询。遇到较为复杂的 SQL 语句,一定要自己拼写的时候,一定要注意严格的判断。没有用 PDO 或者 MySQLi 也可以自己写个 prepared,比如 wordprss db 查询语句,可以看出也是经过严格的类型验证。

function prepare( $query, $args ) {
if ( is_null( $query ) )
return; // This is not meant to be foolproof --
but it will catch obviously incorrect usage.
if ( strpos( $query, '%' ) === false ) {
_doing_it_wrong( 'wpdb::prepare' ,
sprintf ( __( 'The query argument of %s
must have a placeholder.' ), 'wpdb::prepare()' ), '3.9' );
} $args = func_get_args();
array_shift( $args );
// If args were passed as an array (as in vsprintf), move them up
if ( isset( $args[ 0] ) && is_array( $args[0]) )
$args = $args [0];
$query = str_replace( "'%s'", '%s' , $query );
// in case someone mistakenly already singlequoted it
$query = str_replace( '"%s"', '%s' , $query );
// doublequote unquoting
$query = preg_replace( '|(?<!%)%f|' , '%F' , $query );
// Force floats to be locale unaware
$query = preg_replace( '|(?<!%)%s|', "'%s'" , $query );
// quote the strings, avoiding escaped strings like %%s
array_walk( $args, array( $this, 'escape_by_ref' ) );
return @ vsprintf( $query, $args );
}

总结

安全性很重要,也可以看出一个人基本功,项目漏洞百出,扩展性和可维护性再好也没有用。平时多留意,树立安全意识,养成一种习惯,一些基本的安全当然也不会占用用 coding 的时间。养成这个习惯,即便在项目急,时间短的情况一下,依然可以做的质量很高。不要等到自己以后负责的东西,数据库都被拿走了,造成损失才重视。共勉!

php SQL 防注入的一些经验的更多相关文章

  1. SQL防注入程序 v1.0

    /// ***************C#版SQL防注入程序 v1.0************ /// *使用方法: /// 一.整站防注入(推荐) /// 在Global.asax.cs中查找App ...

  2. PHP之SQL防注入代码集合(建站常用)

    SQL防注入代码一 <?php if (!function_exists (quote)) { function quote($var) { if (strlen($var)) { $var=! ...

  3. sql 防注入 维基百科

    http://zh.wikipedia.org/wiki/SQL%E8%B3%87%E6%96%99%E9%9A%B1%E7%A2%BC%E6%94%BB%E6%93%8A SQL攻击(SQL inj ...

  4. 特殊字符的过滤方法,防sql防注入代码的过滤方法

    特殊字符的过滤方法 function strFilter($str){ //特殊字符的过滤方法 $str = str_replace('`', '', $str); $str = str_replac ...

  5. SQL防注入程序

    1.在Global.asax.cs中写入: protected void Application_BeginRequest(Object sender,EventArgs e){      SqlIn ...

  6. PHP SQL防注入

    过年前后在做一个抽奖的东西,需要用户填写中奖信息,为了防止非法用户对数据库进行入侵神马的,于是写下基本的防注入语句,需要用的可以自己封装成一个function. $str = str_replace( ...

  7. 360提供的SQL防注入

    <?php class sqlsafe { private $getfilter = "'|(and|or)\\b.+?(>|<|=|in|like)|\\/\\*.+?\ ...

  8. .net sql 防注入 httpmodule

    1 新建一个类,实现IHttpModule接口 using System; using System.Collections.Generic; using System.Linq; using Sys ...

  9. PHP之SQL防注入代码(360提供)

    <?php class sqlsafe { private $getfilter = "'|(and|or)\\b.+?(>|<|=|in|like)|\\/\\*.+?\ ...

随机推荐

  1. Python实践练习:强口令检测

    题目: 写一个函数,它使用正则表达式,确保传入的口令字符串是强口令.强口令的定义是:长度不少于 8 个字符,同时包含大写和小写字符,至少有一位数字.你可能需要用多个正则表达式来测试该字符串,以保证它的 ...

  2. leetcode19

    class Solution { public: ; ; ListNode* removeNthFromEnd(ListNode* head, int n) { ; ListNode* node = ...

  3. pyqt5 -——介绍及和pycharm的环境搭建

    pyqt5简介: yQt5的类存在与如下模块当中: ● QtCore ● QtGui ● QtWidgets ● QtMultimedia ● QtBluetooth ● QtNetwork ● Qt ...

  4. HTML5-canvas1.0

    HTML5 <canvas> 元素用于图形的绘制,通过脚本 (通常是JavaScript)来完成.<canvas> 标签只是图形容器,您必须使用脚本来绘制图形.你可以通过多种方 ...

  5. android之RefBase

    路径 system core libutils include utils RefBase.h namespace android 命名空间是android class TextOutput;// 这 ...

  6. Spring使用fastjson处理json数据

    1.搭建SpringMVC+spring环境 2.配置web.xml以及springmvc-config.xml,web.xml同Spring使用jackson处理json数据一样,Springmvc ...

  7. JS判断手机端是否安装某应用

    方法一(网页上判断) if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) {   var loadDateTime = new Date() ...

  8. Dart 基础重点截取 Dart 2 20180417

    官网教程 https://www.dartlang.org/guides/language/language-tour dart是一个单线程的语言,没有多线程 Final and const If y ...

  9. [剑指Offer]7-重建二叉树

    链接 https://www.nowcoder.com/practice/8a19cbe657394eeaac2f6ea9b0f6fcf6?tpId=13&tqId=11157&tPa ...

  10. 优秀的 Spring Cloud 开源软件

    Spring Cloud是一系列框架的有序集合.它利用Spring Boot的开发便利性巧妙地简化了分布式系统基础设施的开发,如服务发现注册.配置中心.消息总线.负载均衡.断路器.数据监控等,都可以用 ...