首页 >后端开发 >php教程 >谈谈​PHP防止XSS跨站脚本攻击的方法

谈谈​PHP防止XSS跨站脚本攻击的方法

青灯夜游
青灯夜游转载
2020-07-17 15:41:343669浏览

谈谈​PHP防止XSS跨站脚本攻击的方法

PHP防止XSS跨站脚本攻击的方法:是针对非法的HTML代码包括单双引号等,使用htmlspecialchars()函数

在使用htmlspecialchars()函数的时候注意第二个参数, 直接用htmlspecialchars($string) 的话,第二个参数默认是ENT_COMPAT,函数默认只是转化双引号(“), 不对单引号(‘)做转义.

所以,htmlspecialchars函数更多的时候要加上第二个参数, 应该这样用: htmlspecialchars($string,ENT_QUOTES).当然,如果需要不转化任何引号,用htmlspecialchars($string,ENT_NOQUOTES).

另外, 尽量少用htmlentities, 在全部英文的时候htmlentities和htmlspecialchars没有区别,都可以达到目的.但是,中文情况下, htmlentities却会转化所有的html代码,连同里面的它无法识别的中文字符也给转化了。

htmlentities和htmlspecialchars这两个函数对 '之类的字符串支持不好,都不能转化, 所以用htmlentities和htmlspecialchars转化的字符串只能防止XSS攻击,不能防止SQL注入攻击.

所有有打印的语句如echo,print等 在打印前都要使用htmlentities() 进行过滤,这样可以防止Xss,注意中文要写出htmlentities($name,ENT_NOQUOTES,GB2312) 。

  (1).网页不停地刷新 '9893d28e420a9043ab2a5d868c5b75a9'

  (2).嵌入其它网站的链接 46738f15fd1d4ccfe9ae54bf55ed0994065276f04003e4622c4fe6b64f465b88  除了通过正常途径输入XSS攻击字符外,还可以绕过JavaScript校验,通过修改请求达到XSS攻击的目的.

<?php
//php防注入和XSS攻击通用过滤
$_GET     && SafeFilter($_GET);
$_POST    && SafeFilter($_POST);
$_COOKIE  && SafeFilter($_COOKIE);
  
function SafeFilter (&$arr) 
{
   $ra=Array(&#39;/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/&#39;,&#39;/script/&#39;,&#39;/javascript/&#39;,&#39;/vbscript/&#39;,&#39;/expression/&#39;,&#39;/applet/&#39;
   ,&#39;/meta/&#39;,&#39;/xml/&#39;,&#39;/blink/&#39;,&#39;/link/&#39;,&#39;/style/&#39;,&#39;/embed/&#39;,&#39;/object/&#39;,&#39;/frame/&#39;,&#39;/layer/&#39;,&#39;/title/&#39;,&#39;/bgsound/&#39;
   ,&#39;/base/&#39;,&#39;/onload/&#39;,&#39;/onunload/&#39;,&#39;/onchange/&#39;,&#39;/onsubmit/&#39;,&#39;/onreset/&#39;,&#39;/onselect/&#39;,&#39;/onblur/&#39;,&#39;/onfocus/&#39;,
   &#39;/onabort/&#39;,&#39;/onkeydown/&#39;,&#39;/onkeypress/&#39;,&#39;/onkeyup/&#39;,&#39;/onclick/&#39;,&#39;/ondblclick/&#39;,&#39;/onmousedown/&#39;,&#39;/onmousemove/&#39;
   ,&#39;/onmouseout/&#39;,&#39;/onmouseover/&#39;,&#39;/onmouseup/&#39;,&#39;/onunload/&#39;);
     
   if (is_array($arr))
   {
     foreach ($arr as $key => $value) 
     {
        if (!is_array($value))
        {
          if (!get_magic_quotes_gpc())  //不对magic_quotes_gpc转义过的字符使用addslashes(),避免双重转义。
          {
             $value  = addslashes($value); //给单引号(&#39;)、双引号(")、反斜线(\)与 NUL(NULL 字符)
             #加上反斜线转义
          }
          $value       = preg_replace($ra,&#39;&#39;,$value);     //删除非打印字符,粗暴式过滤xss可疑字符串
          $arr[$key]     = htmlentities(strip_tags($value)); //去除 HTML 和 PHP 标记并转换为 HTML 实体
        }
        else
        {
          SafeFilter($arr[$key]);
        }
     }
   }
}
?>
$str = &#39;www.90boke.com<meta http-equiv="refresh" content="0;">&#39;;
SafeFilter ($str); //如果你把这个注释掉,提交之后就会无休止刷新
echo $str;
//------------------------------php防注入和XSS攻击通用过滤-----Start--------------------------------------------//
function string_remove_xss($html) {
    preg_match_all("/\<([^\<]+)\>/is", $html, $ms);
 
    $searchs[] = &#39;<&#39;;
    $replaces[] = &#39;<&#39;;
    $searchs[] = &#39;>&#39;;
    $replaces[] = &#39;>&#39;;
 
    if ($ms[1]) {
        $allowtags = &#39;img|a|font|div|table|tbody|caption|tr|td|th|br|p|b|strong|i|u|em|span|ol|ul|li|blockquote&#39;;
        $ms[1] = array_unique($ms[1]);
        foreach ($ms[1] as $value) {
            $searchs[] = "<".$value.">";
 
            $value = str_replace(&#39;&&#39;, &#39;_uch_tmp_str_&#39;, $value);
            $value = string_htmlspecialchars($value);
            $value = str_replace(&#39;_uch_tmp_str_&#39;, &#39;&&#39;, $value);
 
            $value = str_replace(array(&#39;\\&#39;, &#39;/*&#39;), array(&#39;.&#39;, &#39;/.&#39;), $value);
            $skipkeys = array(&#39;onabort&#39;,&#39;onactivate&#39;,&#39;onafterprint&#39;,&#39;onafterupdate&#39;,&#39;onbeforeactivate&#39;,&#39;onbeforecopy&#39;,&#39;onbeforecut&#39;,&#39;onbeforedeactivate&#39;,
                    &#39;onbeforeeditfocus&#39;,&#39;onbeforepaste&#39;,&#39;onbeforeprint&#39;,&#39;onbeforeunload&#39;,&#39;onbeforeupdate&#39;,&#39;onblur&#39;,&#39;onbounce&#39;,&#39;oncellchange&#39;,&#39;onchange&#39;,
                    &#39;onclick&#39;,&#39;oncontextmenu&#39;,&#39;oncontrolselect&#39;,&#39;oncopy&#39;,&#39;oncut&#39;,&#39;ondataavailable&#39;,&#39;ondatasetchanged&#39;,&#39;ondatasetcomplete&#39;,&#39;ondblclick&#39;,
                    &#39;ondeactivate&#39;,&#39;ondrag&#39;,&#39;ondragend&#39;,&#39;ondragenter&#39;,&#39;ondragleave&#39;,&#39;ondragover&#39;,&#39;ondragstart&#39;,&#39;ondrop&#39;,&#39;onerror&#39;,&#39;onerrorupdate&#39;,
                    &#39;onfilterchange&#39;,&#39;onfinish&#39;,&#39;onfocus&#39;,&#39;onfocusin&#39;,&#39;onfocusout&#39;,&#39;onhelp&#39;,&#39;onkeydown&#39;,&#39;onkeypress&#39;,&#39;onkeyup&#39;,&#39;onlayoutcomplete&#39;,
                    &#39;onload&#39;,&#39;onlosecapture&#39;,&#39;onmousedown&#39;,&#39;onmouseenter&#39;,&#39;onmouseleave&#39;,&#39;onmousemove&#39;,&#39;onmouseout&#39;,&#39;onmouseover&#39;,&#39;onmouseup&#39;,&#39;onmousewheel&#39;,
                    &#39;onmove&#39;,&#39;onmoveend&#39;,&#39;onmovestart&#39;,&#39;onpaste&#39;,&#39;onpropertychange&#39;,&#39;onreadystatechange&#39;,&#39;onreset&#39;,&#39;onresize&#39;,&#39;onresizeend&#39;,&#39;onresizestart&#39;,
                    &#39;onrowenter&#39;,&#39;onrowexit&#39;,&#39;onrowsdelete&#39;,&#39;onrowsinserted&#39;,&#39;onscroll&#39;,&#39;onselect&#39;,&#39;onselectionchange&#39;,&#39;onselectstart&#39;,&#39;onstart&#39;,&#39;onstop&#39;,
                    &#39;onsubmit&#39;,&#39;onunload&#39;,&#39;javascript&#39;,&#39;script&#39;,&#39;eval&#39;,&#39;behaviour&#39;,&#39;expression&#39;,&#39;style&#39;,&#39;class&#39;);
            $skipstr = implode(&#39;|&#39;, $skipkeys);
            $value = preg_replace(array("/($skipstr)/i"), &#39;.&#39;, $value);
            if (!preg_match("/^[\/|\s]?($allowtags)(\s+|$)/is", $value)) {
                $value = &#39;&#39;;
            }
            $replaces[] = empty($value) ? &#39;&#39; : "<" . str_replace(&#39;"&#39;, &#39;"&#39;, $value) . ">";
        }
    }
    $html = str_replace($searchs, $replaces, $html);
 
    return $html;
}
//php防注入和XSS攻击通用过滤 
function string_htmlspecialchars($string, $flags = null) {
    if (is_array($string)) {
        foreach ($string as $key => $val) {
            $string[$key] = string_htmlspecialchars($val, $flags);
        }
    } else {
        if ($flags === null) {
            $string = str_replace(array(&#39;&&#39;, &#39;"&#39;, &#39;<&#39;, &#39;>&#39;), array(&#39;&&#39;, &#39;"&#39;, &#39;<&#39;, &#39;>&#39;), $string);
            if (strpos($string, &#39;&#&#39;) !== false) {
                $string = preg_replace(&#39;/&((#(\d{3,5}|x[a-fA-F0-9]{4}));)/&#39;, &#39;&\\1&#39;, $string);
            }
        } else {
            if (PHP_VERSION < &#39;5.4.0&#39;) {
                $string = htmlspecialchars($string, $flags);
            } else {
                if (!defined(&#39;CHARSET&#39;) || (strtolower(CHARSET) == &#39;utf-8&#39;)) {
                    $charset = &#39;UTF-8&#39;;
                } else {
                    $charset = &#39;ISO-8859-1&#39;;
                }
                $string = htmlspecialchars($string, $flags, $charset);
            }
        }
    }
 
    return $string;
}

//------------------php防注入和XSS攻击通用过滤-----End--------------------------------------------//

PHP中的设置 

PHP5.2以上版本已支持HttpOnly参数的设置,同样也支持全局的HttpOnly的设置,在php.ini中

----------------------------------------------------- 
 session.cookie_httponly = 
-----------------------------------------------------

设置其值为1或者TRUE,来开启全局的Cookie的HttpOnly属性,当然也支持在代码中来开启: 

<?php ini_set("session.cookie_httponly", 1);   
// or session_set_cookie_params(0, NULL, NULL, NULL, TRUE);   
?>

Cookie操作函数setcookie函数和setrawcookie函数也专门添加了第7个参数来做为HttpOnly的选项,开启方法为: 

<?php  
setcookie("abc", "test", NULL, NULL, NULL, NULL, TRUE);   
setrawcookie("abc", "test", NULL, NULL, NULL, NULL, TRUE);  
?>

相关推荐:PHP教程

以上是谈谈​PHP防止XSS跨站脚本攻击的方法的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:cnblogs.com。如有侵权,请联系admin@php.cn删除