XSS攻击

一、什么是XSS攻击

跨站脚本攻击(Cross Site Scripting),攻击者往Web页面里插入恶意Script代码,当用户浏览该页之时,嵌入其中Web里面的Script代码会被执行,从而达到恶意攻击用户的目的。

二、转化的思想防范xss攻击

转化的思想:将输入内容中的<>转化为html实体字符。

原生php中对xss攻击进行防范,使用htmlspecialchars函数,将用户输入的字符串中的特殊字符,比如<> 转化为html实体字符。

封装使用步骤:

① 使用composer执行命令,安装 ezyang/htmlpurifier 扩展类库
项目目录下

composer require ezyang/htmlpurifier

② 在app/common.php中定义remove_xss函数

if (!function_exists('remove_xss')) {
    //使用htmlpurifier防范xss攻击
    function remove_xss($string){
        //相对index.php入口文件,引入HTMLPurifier.auto.php核心文件
        //require_once './plugins/htmlpurifier/HTMLPurifier.auto.php';
        // 生成配置对象
        $cfg = HTMLPurifier_Config::createDefault();
        // 以下就是配置:
        $cfg -> set('Core.Encoding', 'UTF-8');
        // 设置允许使用的HTML标签
        $cfg -> set('HTML.Allowed','div,b,strong,i,em,a[href|title],ul,ol,li,br,p[style],span[style],img[width|height|alt|src]');
        // 设置允许出现的CSS样式属性
        $cfg -> set('CSS.AllowedProperties', 'font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,color,background-color,text-align');
        // 设置a标签上是否允许使用target="_blank"
        $cfg -> set('HTML.TargetBlank', TRUE);
        // 使用配置生成过滤用的对象
        $obj = new HTMLPurifier($cfg);
        // 过滤字符串
        return $obj -> purify($string);
    }
}

③测试结果

参数一为要接收的值,参数二为默认值,参数三为方法名

    $data = request()->post('','','remove_xss');
本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!