程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> PHP綜合 >> PHP利用str_replace防注入的方法

PHP利用str_replace防注入的方法

編輯:PHP綜合

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;
    }
    ?>

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved