php SQL 防注入的一些经验
产生原因
一方面自己没这方面的意识,有些数据没有经过严格的验证,然后直接拼接 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 防注入的一些经验的更多相关文章
- SQL防注入程序 v1.0
/// ***************C#版SQL防注入程序 v1.0************ /// *使用方法: /// 一.整站防注入(推荐) /// 在Global.asax.cs中查找App ...
- PHP之SQL防注入代码集合(建站常用)
SQL防注入代码一 <?php if (!function_exists (quote)) { function quote($var) { if (strlen($var)) { $var=! ...
- 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 ...
- 特殊字符的过滤方法,防sql防注入代码的过滤方法
特殊字符的过滤方法 function strFilter($str){ //特殊字符的过滤方法 $str = str_replace('`', '', $str); $str = str_replac ...
- SQL防注入程序
1.在Global.asax.cs中写入: protected void Application_BeginRequest(Object sender,EventArgs e){ SqlIn ...
- PHP SQL防注入
过年前后在做一个抽奖的东西,需要用户填写中奖信息,为了防止非法用户对数据库进行入侵神马的,于是写下基本的防注入语句,需要用的可以自己封装成一个function. $str = str_replace( ...
- 360提供的SQL防注入
<?php class sqlsafe { private $getfilter = "'|(and|or)\\b.+?(>|<|=|in|like)|\\/\\*.+?\ ...
- .net sql 防注入 httpmodule
1 新建一个类,实现IHttpModule接口 using System; using System.Collections.Generic; using System.Linq; using Sys ...
- PHP之SQL防注入代码(360提供)
<?php class sqlsafe { private $getfilter = "'|(and|or)\\b.+?(>|<|=|in|like)|\\/\\*.+?\ ...
随机推荐
- maven的依赖管理详细
依赖管理 Jar包的管理 需求:整合struts2 页面上传一个客户id 跳转页面 1 添加依赖: 打开maven仓库的视图: 2 重建索引 1. 创建maven项目(同上) 2. 跳过骨架(同上 ...
- 非常优秀的swiper插件————幻灯片播放、图片轮播
http://www.idangero.us/ http://www.swiper.com.cn/ Swiper中文网 2015-10-15 SuperSlide2: (这是个PC用的滚屏插件,看着不 ...
- Java 原子语义同步的底层实现
原子语义同步的底层实现 volatile volatile只能保证变量对各个线程的可见性,但不能保证原子性.关于 Java语言 volatile 的使用方法就不多说了,我的建议是 除了 配合packa ...
- 1. Spring基于xml加载和读取properties文件配置
在src目录下,新建test.properties配置文件,内容如下 name=root password=123456 logArchiveCron=0/5 * * * * ? 一种是使用sprin ...
- Visual Studio资源汇总
Visual Studio 2015:http://tieba.baidu.com/p/3442930798Visual Studio 2013:http://tieba.baidu.com/p/34 ...
- leetcode215
class Solution { public: int findKthLargest(vector<int>& nums, int k) { sort(nums.begin(), ...
- BBS(第一天)项目之 注册功能实现通过forms验证与 前端ajax请求触发查询数据库判断用户是否存在的功能实现
1.BBS项目之注册功能通过forms验证 from django import forms from blog.models import User from django.contrib.auth ...
- JavaScript学习-1
本章目录: --------①数据类型. --------②定义变量. --------③类型转换. --------④运算符. --------⑤比较符. --------⑥if语句. ------ ...
- Aplication的意义和生命周期,与Context的关系,以及关于Aplication和Context相关问题的记录和解决办法
Context详解地址链接: http://blog.csdn.net/qinjuning/article/details/7310620 Application是一个应用中有且仅有一个的全局共享变量 ...
- css一些特殊选择器
css一些特殊选择器1.在box中,从第几个div开始选择,以后的都会选择到,以下代码表示从#box里面的第二个div开始选择:#box div:nth-of-type(n+2){}2.选择奇数个:d ...