0
点赞
收藏
分享

微信扫一扫

tp6防范xss攻击的几种方法

棒锤_45f2 2022-01-13 阅读 114

首先配置一个get方法的路由,方便我们查看效果

路由:

Route::get('script','goods/script');

页面的地址栏:

控制器的方法:

public function script(){
        $data = \request()->get('name');
        echo $data;
    }

按照以上的配置完成后,页面先弹出一个“xss攻击”的弹框,点击确定后会在页面输出123;

接下来我们来谈一谈防范xss攻击的三种方法:

第一种:使用PHP的内置函数----->htmlspecialchars()

public function script(){
        $data = \request()->get('name');
        //第一种直接使用PHP内置函数
        $data = htmlspecialchars($data);
        echo $data;
    }

 第二种:在tp6框架中找到:app/Request.php 设置全局的过滤信息

// 应用请求对象类
class Request extends \think\Request
{
    //第二种:定义全局过滤信息
    protected $filter = 'htmlspecialchars';
}

第三种:封装一个公共的方法:remove_xss 

首先使用composer安装扩展:composer require ezyang/htmlpurifier

参考官方网址:http://htmlpurifier.org/download

a

// 应用公共文件
if (!function_exists('remove_xss')){
    function remove_xss($dirty_html){
        //相对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);
        $purifier = new HTMLPurifier();
        return $purifier->purify($dirty_html);
    }
}

b

// 应用公共文件
if (!function_exists('remove_xss')){
    function remove_xss($dirty_html){
        $purifier = new HTMLPurifier();
        return $purifier->purify($dirty_html);
    }
}

 

 public function script(){
        $data = \request()->get('name');
        //第三种设置一个公共方法:remove_xss
        $data = \request()->get('name','','remove_xss');
        echo $data;
    }
举报

相关推荐

0 条评论