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 相关文章推荐
PHP的ASP防火墙
Oct 09 PHP
一些php项目中比较通用的php自建函数的详解
Jun 06 PHP
解析smarty 截取字符串函数 truncate的用法介绍
Jun 20 PHP
php获取远程图片体积大小的实例
Nov 12 PHP
php编写的简单页面跳转功能实现代码
Nov 27 PHP
php反射应用示例
Feb 25 PHP
PHP 使用redis简单示例分享
Mar 05 PHP
php从数据库查询结果生成树形列表的方法
Apr 17 PHP
php fread读取文件注意事项
Sep 24 PHP
PHP7扩展开发之hello word实现方法详解
Jan 15 PHP
php中关于换行的实例写法
Sep 26 PHP
PHP上传图片到数据库并显示的实例代码
Dec 20 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
将兴奋、喜悦和坎加斯带到戴安娜:亚马逊公主
2020/03/03 欧美动漫
一个好用的分页函数
2006/11/16 PHP
检查用户名是否已在mysql中存在的php写法
2014/01/20 PHP
php+mysqli批量查询多张表数据的方法
2015/01/29 PHP
获取非最后一列td值并将title设为该值的方法
2013/10/30 Javascript
BootStrap的弹出框(Popover)支持鼠标移到弹出层上弹窗层不隐藏的原因及解决办法
2016/04/03 Javascript
jQuery控制div实现随滚动条滚动效果
2016/06/07 Javascript
Angular ng-repeat 对象和数组遍历实例
2016/09/14 Javascript
JS用斜率判断鼠标进入DIV四个方向的方法
2016/11/07 Javascript
Bootstrap 响应式实用工具实例详解
2017/03/29 Javascript
不得不看之JavaScript构造函数及new运算符
2017/08/21 Javascript
JS与CSS3实现图片响应鼠标移动放大效果示例
2018/05/04 Javascript
JS实现调用本地摄像头功能示例
2018/05/18 Javascript
jQuery HTML获取内容和属性操作实例分析
2020/05/20 jQuery
Element InputNumber 计数器的实现示例
2020/08/03 Javascript
[40:48]DOTA2上海特级锦标赛D组败者赛 Liquid VS COL第二局
2016/02/28 DOTA
[54:58]完美世界DOTA2联赛PWL S2 LBZS vs Rebirth 第一场 11.25
2020/11/25 DOTA
[01:08:29]DOTA2-DPC中国联赛定级赛 RNG vs Aster BO3第一场 1月9日
2021/03/11 DOTA
django 自定义用户user模型的三种方法
2014/11/18 Python
python处理csv数据的方法
2015/03/11 Python
dataframe设置两个条件取值的实例
2018/04/12 Python
Python键盘输入转换为列表的实例
2018/06/23 Python
Python使用gRPC传输协议教程
2018/10/16 Python
python实现批量注册网站用户的示例
2019/02/22 Python
python 一个figure上显示多个图像的实例
2019/07/08 Python
Python环境搭建过程从安装到Hello World
2021/02/05 Python
c/c++某大公司的两道笔试题
2014/02/02 面试题
医学护理系毕业生求职信
2013/10/01 职场文书
教师批评与自我批评剖析材料
2014/10/16 职场文书
2015年餐厅服务员工作总结
2015/04/23 职场文书
新学期感想
2015/08/10 职场文书
SQLServer中exists和except用法介绍
2021/12/04 SQL Server
Python Pandas读取Excel日期数据的异常处理方法
2022/02/28 Python
Python读取和写入Excel数据
2022/04/20 Python
MySQL 条件查询的常用操作
2022/04/28 MySQL
win10电脑老是死机怎么办?win10系统老是死机的解决方法
2022/08/05 数码科技