-
PHP利用str_replace()函数防注入
str_replace()函数的使用就是用来替换指定字符了,那么我们正好可以利用它这一点来过滤敏感字符以太到防注入的效果,下面我来给大家总结了一些方法,给大家分享一下.
PHP各种过滤字符函数,代码如下:
- <?php
- /**
- * 安全过滤函数
- *
- * @param $string
- * @return string
- */
- function safe_replace($string) {
- $string = str_replace('%20','',$string);
- $string = str_replace('%27','',$string);
- $string = str_replace('%2527','',$string);
- $string = str_replace('*','',$string);
- $string = str_replace('"','"',$string);
- $string = str_replace("'",'',$string);
- $string = str_replace('"','',$string);
- $string = str_replace(';','',$string);
- $string = str_replace('<','<',$string);
- $string = str_replace('>','>',$string);
- $string = str_replace("{",'',$string);
- $string = str_replace('}','',$string);
- $string = str_replace('','',$string);
- return $string;
- }
- ?>
- <?php
- /**
- * 返回经addslashes处理过的字符串或数组
- * @param $string 需要处理的字符串或数组
- * @return mixed
- */
- function new_addslashes($string) {
- if(!is_array($string)) return addslashes($string);
- foreach($string as $key => $val) $string[$key] = new_addslashes($val);
- return $string;
- }
- ?>
- <?php
- //对请求的字符串进行安全处理
- /*
- $safestep
- 0 为不处理,
- 1 为禁止不安全HTML内容(javascript等),
- 2 完全禁止HTML内容,并替换部份不安全字符串(如:eval(、union、CONCAT(、--、等)
- */
- function StringSafe($str, $safestep=-1){
- $safestep = ($safestep > -1) ? $safestep : 1;
- if($safestep == 1){
- $str = preg_replace("#script:#i", "script:", $str);
- $str = preg_replace("#<[/]{0,1}(link|meta|ifr|fra|scr)[^>]*>#isU", '', $str);
- $str = preg_replace("#[ ]{1,}#", ' ', $str);
- return $str;
- }else if($safestep == 2){
- $str = addslashes(htmlspecialchars(stripslashes($str)));
- $str = preg_replace("#eval#i", 'eval', $str);
- $str = preg_replace("#union#i", 'union', $str);
- $str = preg_replace("#concat#i", 'concat', $str);
- $str = preg_replace("#--#", '--', $str);
- $str = preg_replace("#[ ]{1,}#", ' ', $str);
- return $str;
- }else{
- return $str;
- }
- }
- ?>
- <?php
- /**
- +----------------------------------------------------------
- * 输出安全的html,用于过滤危险代码
- +----------------------------------------------------------
- * @access public
- +----------------------------------------------------------
- * @param string $text 要处理的字符串
- * @param mixed $tags 允许的标签列表,如 table|td|th|td
- +----------------------------------------------------------
- * @return string
- +----------------------------------------------------------
- */
- static public function safeHtml($text, $tags = null)
- {
- $text = trim($text);
- //完全过滤注释
- $text = preg_replace('/<!--?.*-->/','',$text);
- //完全过滤动态代码
- $text = preg_replace('/<?|?'.'>/','',$text);
- //完全过滤js
- $text = preg_replace('/<script?.*/script>/','',$text);
- $text = str_replace('[','[',$text);
- $text = str_replace(']',']',$text);
- $text = str_replace('|','|',$text);
- //过滤换行符
- $text = preg_replace('/ ? /','',$text);
- //br
- $text = preg_replace('/<br(s/)?'.'>/i','[br]',$text);
- $text = preg_replace('/([br]s*){10,}/i','[br]',$text);
- //过滤危险的属性,如:过滤on事件lang js
- while(preg_match('/(<[^><]+)(lang|on|action|background|codebase|dynsrc|lowsrc)[^><]+/i',$text,$mat)){
- $text=str_replace($mat[0],$mat[1],$text);
- }
- while(preg_match('/(<[^><]+)(window.|javascript:|js:|about:|file:|document.|vbs:|cookie)([^><]*)/i',$text,$mat)){
- $text=str_replace($mat[0],$mat[1].$mat[3],$text);
- }
- if( emptyempty($allowTags) ) { $allowTags = self::$htmlTags['allow']; }
- //允许的HTML标签
- $text = preg_replace('/<('.$allowTags.')( [^><[]]*)>/i','[12]',$text);
- //过滤多余html
- if ( emptyempty($banTag) ) { $banTag = self::$htmlTags['ban']; }
- $text = preg_replace('/</?('.$banTag.')[^><]*>/i','',$text);
- //过滤合法的html标签
- while(preg_match('/<([a-z]+)[^><[]]*>[^><]*</1>/i',$text,$mat)){
- $text=str_replace($mat[0],str_replace('>',']',str_replace('<','[',$mat[0])),$text);
- }
- //转换引号
- while(preg_match('/([[^[]]*=s*)("|')([^2=[]]+)2([^[]]*])/i',$text,$mat)){
- $text=str_replace($mat[0],$mat[1].'|'.$mat[3].'|'.$mat[4],$text);
- }
- //空属性转换
- $text = str_replace('''','||',$text);
- $text = str_replace('""','||',$text);
- //过滤错误的单个引号
- while(preg_match('/[[^[]]*("|')[^[]]*]/i',$text,$mat)){
- $text=str_replace($mat[0],str_replace($mat[1],'',$mat[0]),$text);
- }
- //转换其它所有不合法的 < >
- $text = str_replace('<','<',$text);
- $text = str_replace('>','>',$text);
- $text = str_replace('"','"',$text);
- //反转换
- $text = str_replace('[','<',$text);
- $text = str_replace(']','>',$text);
- $text = str_replace('|','"',$text);
- //过滤多余空格
- $text = str_replace(' ',' ',$text);
- return $text;
- }
- ?>
- <?php
- function RemoveXSS($val) {
- // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
- // this prevents some character re-spacing such as <javascript>
- // note that you have to handle splits with , , and later since they *are* allowed in some // inputs
- $val = preg_replace('/([x00-x08,x0b-x0c,x0e-x19])/', '', $val);
- // straight replacements, the user should never need these since they're normal characters
- // this prevents like <IMG SRC=@avascript:alert('XSS')>
- $search = 'abcdefghijklmnopqrstuvwxyz';
- $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
- $search .= '1234567890!@#$%^&*()';
- $search .= '~`";:?+/={}[]-_|'';
- for ($i = 0; $i < strlen($search); $i++) {
- // ;? matches the ;, which is optional
- // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars
- // @ @ search for the hex values
- $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val);//with a ;
- // @ @ 0{0,7} matches '0' zero to seven times
- $val = preg_replace('/(�{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
- }
- // now the only remaining whitespace attacks are , , and
- $ra1 = Array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
- $ra2 = Array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
- $ra = array_merge($ra1, $ra2);
- $found = true; // keep replacing as long as the previous round replaced something
- while ($found == true) {
- $val_before = $val;
- for ($i = 0; $i < sizeof($ra); $i++) {
- $pattern = '/';
- for ($j = 0; $j < strlen($ra[$i]); $j++) {
- if ($j > 0) {
- $pattern .= '(';
- $pattern .= '(&#[xX]0{0,8}([9ab]);)';
- $pattern .= '|';
- $pattern .= '|(�{0,8}([9|10|13]);)';
- $pattern .= ')*';
- }
- $pattern .= $ra[$i][$j];
- }
- $pattern .= '/i';
- $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
- $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
- if ($val_before == $val) {
- // no replacements were made, so exit the loop
- $found = false;
- }
- } //开源代码phpfensi.com
- }
- return $val;
- }
- ?>
出处:http://www.phpfensi.com/php/20140822/4615.html
栏目列表
最新更新
nodejs爬虫
Python正则表达式完全指南
爬取豆瓣Top250图书数据
shp 地图文件批量添加字段
爬虫小试牛刀(爬取学校通知公告)
【python基础】函数-初识函数
【python基础】函数-返回值
HTTP请求:requests模块基础使用必知必会
Python初学者友好丨详解参数传递类型
如何有效管理爬虫流量?
SQL SERVER中递归
2个场景实例讲解GaussDB(DWS)基表统计信息估
常用的 SQL Server 关键字及其含义
动手分析SQL Server中的事务中使用的锁
openGauss内核分析:SQL by pass & 经典执行
一招教你如何高效批量导入与更新数据
天天写SQL,这些神奇的特性你知道吗?
openGauss内核分析:执行计划生成
[IM002]Navicat ODBC驱动器管理器 未发现数据
初入Sql Server 之 存储过程的简单使用
这是目前我见过最好的跨域解决方案!
减少回流与重绘
减少回流与重绘
如何使用KrpanoToolJS在浏览器切图
performance.now() 与 Date.now() 对比
一款纯 JS 实现的轻量化图片编辑器
关于开发 VS Code 插件遇到的 workbench.scm.
前端设计模式——观察者模式
前端设计模式——中介者模式
创建型-原型模式