PHP利用str_replace防注入的方法


Posted in PHP onNovember 10, 2013

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( empty($allowTags) ) { $allowTags = self::$htmlTags['allow']; }
           //允许的HTML标签
           $text =  preg_replace('/<('.$allowTags.')( [^><[]]*)>/i','[12]',$text);
           //过滤多余html
           if ( empty($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; 
               } 
           } 
       } 
       return $val; 
    }
    ?>
PHP 相关文章推荐
杏林同学录(七)
Oct 09 PHP
echo(),print(),print_r()之间的区别?
Nov 19 PHP
PHP set_time_limit(0)长连接的实现分析
Mar 02 PHP
Laravel 5框架学习之向视图传送数据(进阶篇)
Apr 08 PHP
PHP+AJAX实现投票功能的方法
Sep 28 PHP
php常量详细解析
Oct 27 PHP
WordPress网站性能优化指南
Nov 18 PHP
php获取一定范围内取N个不重复的随机数
May 28 PHP
Yii2 hasOne(), hasMany() 实现三表关联的方法(两种)
Feb 15 PHP
PHP一致性hash分布式算法封装类定义与用法示例
Aug 04 PHP
PHP命名空间与自动加载类详解
Sep 04 PHP
thinkphp5框架结合mysql实现微信登录和自定义分享链接与图文功能示例
Aug 13 PHP
PHP加密扩展库Mcrypt安装和实例
Nov 10 #PHP
php中autoload的用法总结
Nov 08 #PHP
PHP用身份证号获取星座和生肖的方法
Nov 07 #PHP
php旋转图片90度的方法
Nov 07 #PHP
提高PHP编程效率的方法
Nov 07 #PHP
PHP imagegrabscreen和imagegrabwindow(截取网站缩略图)的实例代码
Nov 07 #PHP
php获取汉字首字母的函数
Nov 07 #PHP
You might like
phpmyadmin的#1251问题
2006/11/25 PHP
域名和cookie问题(域名后缀)
2012/10/10 PHP
php中判断数组是一维,二维,还是多维的解决方法
2013/05/04 PHP
php视频拍照上传头像功能实现代码分享
2015/10/08 PHP
总结PHP代码规范、流程规范、git规范
2018/06/18 PHP
PHP 二维array转换json的实例讲解
2018/08/21 PHP
PHP设计模式(八)装饰器模式Decorator实例详解【结构型】
2020/05/02 PHP
javascript打开新窗口同时关闭旧窗口
2009/01/16 Javascript
JavaScript 实现鼠标拖动元素实例代码
2014/02/24 Javascript
js文件包含的几种方式介绍
2014/09/28 Javascript
原生JS和JQuery动态添加、删除表格行的方法
2015/05/28 Javascript
简介JavaScript中的getUTCFullYear()方法的使用
2015/06/10 Javascript
javascript中apply/call和bind的使用
2017/02/15 Javascript
AngularJS中控制器函数的定义与使用方法示例
2017/10/10 Javascript
利用Javascript开发一个二维周视图日历
2017/12/14 Javascript
jQuery进阶实践之利用最优雅的方式如何写ajax请求
2017/12/20 jQuery
解决在vue项目中,发版之后,背景图片报错,路径不对的问题
2018/03/06 Javascript
vue 实现数字滚动增加效果的实例代码
2018/07/06 Javascript
详解React 的几种条件渲染以及选择
2018/10/23 Javascript
监控Nodejs的性能实例代码
2019/07/02 NodeJs
python自动登录12306并自动点击验证码完成登录的实现源代码
2018/04/25 Python
Python facenet进行人脸识别测试过程解析
2019/08/16 Python
python下载卫星云图合成gif的方法示例
2020/02/18 Python
matlab、python中矩阵的互相导入导出方式
2020/06/01 Python
Python应用实现处理excel数据过程解析
2020/06/19 Python
使用Python画了一棵圣诞树的实例代码
2020/11/27 Python
SmartBuyGlasses美国官网:太阳眼镜和眼镜
2017/08/20 全球购物
IGK Hair官网:喷雾、洗发水、护发素等
2020/11/03 全球购物
品质主管岗位职责
2014/03/16 职场文书
学生个人自我鉴定
2014/03/26 职场文书
办公室主任岗位职责范本
2015/03/31 职场文书
2015年宣传工作总结
2015/04/08 职场文书
python引入其他文件夹下的py文件具体方法
2021/05/23 Python
教你利用python实现企业微信发送消息
2021/05/23 Python
分享7个 Python 实战项目练习
2022/03/03 Python
Python函数对象与闭包函数
2022/04/13 Python