一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

php xss 攻击防范代码

时间:2014-02-27 编辑:简简单单 来源:一聚教程网

 

例子

最简单的方法利用php自带的htmlspecialchars函数 将字符内容转化为html实体

 代码如下 复制代码

  if (isset($_POST['name'])){
    $str = trim($_POST['name']);  //清理空格
    $str = strip_tags($str);   //过滤html标签
    $str = htmlspecialchars($str);   //将字符内容转化为html实体
    $str = addslashes($str);
    echo $str;
}
?>




例子

对 htmlspecialchars 函数的封装的同时还替换一些己知可能有危险的字符

 代码如下 复制代码

/**
 * 对 htmlspecialchars 函数的封装
 * @param $item
 * @param string $encoding
 * @return array|mixed|string
 */
function clear_xss($item, $encoding='UTF-8') {
    if (is_array($item)) {
        return array_map('clear_xss', $item);
    } else {
        $item = htmlspecialchars($item, ENT_QUOTES, $encoding);

        //www.111com.net下面是从CI里拿过来的
        $no   = '/%0[0-8bcef]/';
        $item = preg_replace($no, '', $item);
        $no   = '/%1[0-9a-f]/';
        $item = preg_replace($no, '', $item);
        $no   = '/[- -]+/S';
        $item = preg_replace($no, '', $item);
        return $item;
    }
}


这里提供一个过滤非法脚本的函数:

 代码如下 复制代码

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  
   // note that you have to handle splits with , , and later since they *are* allowed in some inputs 
   $val = preg_replace('/([-][ - ][- ])/', '', $val); 

   // straight replacements, the user should never need these since they're normal characters 
   // this prevents like  
   $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('/(&#[x|X]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 www.111Cn.net 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 .= '(&#[x|X]0{0,8}([9][a][b]);?)?'; 
               $pattern .= '|(�{0,8}([9][10][13]);?)?'; 
               $pattern .= ')?'; 
            } 
            $pattern .= $ra[$i][$j]; 
         } 
         $pattern .= '/i'; 
         $replacement = substr($ra[$i], 0, 2).''.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; 
         } 
      } 
   } 
}

最后面这个函数主要是用到了国外一些高手写了,对己知危险的函数知道的更多了,所以我们把它全放进去然后进行替换操作了。

还有一点一聚教程小编得提醒你的是有些朋友使用htmlentities()来过滤了,这个函数默认编码为 ISO-8859-1,如果你的非法脚本编码为其它,那么可能无法过滤掉,同时浏览器却可以识别和执行哦,所以得想办法解决呀。

 

热门栏目