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)|\\/\\*.+?\ ...
随机推荐
- LeetCode contest-95[876,877,👁878]
876. Middle of the Linked List first submission # Definition for singly-linked list. # class ListNod ...
- 编写Servlet 实例 -Shopping网站时,遇到的几个问题
问题一.在Web 上运行时,用JDBC链接MySQL总是出错,一直出现驱动加载失败 ------提示java.lang.ClassNotFoundException.解决方案:将数据库驱动jar文件导 ...
- Linux输入子系统详解
input输入子系统框架 linux输入子系统(linux input subsystem)从上到下由三层实现,分别为:输入子系统事件处理层(EventHandler).输入子系统核心层(Input ...
- ubuntu16下用QT5实现对话框应用
ubuntu16下用QT5,实现对话框程序,步骤:生成界面Dialog.ui,将它应用到主程序,通过主程序显示. 一 界面练习 1 Dialog.ui界面生成 在命令行输入:designer 进入界面 ...
- apache配置报错:Unrecognized LogFormat directive %I
跟着阿里云调日志教程(https://help.aliyun.com/document_detail/87740.html)时出现报错: AH00526: Syntax error on line . ...
- 双网卡Iptables端口转发
当前场景如下 跳板机A是双网卡,有一个内网IP和一个公网IP 内网IP: 10.0.10.30 外网IP: 58.68.255.123 内网机器:10.0.30.88,可以和10.0.10.30通讯 ...
- tensorflow/pytorch/mxnet的pip安装,非源代码编译,基于cuda10/cudnn7.4.1/ubuntu18.04.md
os安装 目前对tensorflow和cuda支持最好的是ubuntu的18.04 ,16.04这种lts,推荐使用18.04版本.非lts的版本一般不推荐. Windows倒是也能用来装深度GPU环 ...
- linux check
建议安装chkrootkit.rkhunter.Lynis.ISPProtect这类安全工具,定期做扫描
- html css col-md-offset
有的时候,我们不想让两个相邻的列挨在一起,这时候利用栅格系统的列偏移(offset)功能来实现,而不必再定义margin值.使用.col-md-offset-*形式的样式就可以将列偏移到右侧.例如,. ...
- myeclise 安装
安装.破解步骤都在gaobo百度云/工具/开发工具 安装后配置环境变量: