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)|\\/\\*.+?\ ...
随机推荐
- CentOS 7 无法yum安装解决方法
1)下载repo文件 wget http://mirrors.aliyun.com/repo/Centos-7.repo 2)备份并替换系统的repo文件 .repo /etc/yum.repos.d ...
- Unity与安卓IOS交互
记录下 安卓与Unity交互中 跳坑 找到的资料. <1>建立交互 http://blog.csdn.net/lizhengwei1989/article/details/54631 ...
- cmake 指定连接的opencv版本
我们通常需要使用不同版本的opencv,这时候如果用cmake构建工程,直接指定本地编译好的路径就可以,在CMakeLists.txt中添加: set(OpenCV_DIR "/xxx/wo ...
- 360浏览器对CSS的补齐
360浏览器对很多CSS不兼容,导致了很多代码显示不正常, 常见的解决方法: 很多人在源代码加了<meta content=\"IE=edge\" http-equiv=\& ...
- ucore-lab1-练习5report
实验5--实现函数调用堆栈跟踪函数 需要完成kdebug.c中函数print_stackframe的实现,可以通过函数print_stackframe来跟踪函数调用堆栈中记录的返回地址. 一.函数堆栈 ...
- centos部署redis主从
安装环境 CentOS 6.5 .CentOS 7.4 主Redis:10.159.44.175 从Redis: 10.159.44.176.10.159.44.177 Redis下载和安装 在3台机 ...
- KBEngine 编译出现 MSB802 无法找到v140的生成工具
我用的vs版本是vs2017professional版本,并未安装所有的工具 在编译kbengine源码时候出现 MSB802 无法找到v140的生成工具错误 修复办法在菜单栏选择 工具--> ...
- mybatis多表关联
1.比如我有两个一个是菜单表t_menu,一个是权限表t_jurisdiction.表结构如下: 2.我想要将这两个表关联,查询特定的role_id下的菜单情况,这也是我们经常用在权限管理系统中的做法 ...
- 244. Shortest Word Distance II 实现数组中的最短距离单词
[抄题]: Design a class which receives a list of words in the constructor, and implements a method that ...
- centos7 微信安装
安装过程如下: ,下载最新版本tar.gz压缩包 wget https://github.com/geeeeeeeeek/electronic-wechat/releases/download/V2. ...