Laravel—Purifier扩展包防止XSS攻击

HTMLPurifier 是基于 PHP 编写的富文本 HTML 过滤器,通常我们可以使用它来防止 XSS 跨站攻击。

针对XSS跨站攻击,一般有两种方法避免

  1. 对用户提交的数据进行过滤
  2. 对显示数据进行特殊处理,一般用htmlspecialchars()实体化处理

laravel的blade引擎中{{ }}会自动调用PHP的htmlspecialchars()来避免XSS攻击,而HTMLPurifier就是第一种方法,其实就类似于白名单机制,不在白名单的内容会被过滤掉

具体可以查看官网:http://htmlpurifier.org/

1、安装

composer require "mews/purifier:~2.0"

2、生成配置文件

php artisan vendor:publish --provider="Mews\Purifier\PurifierServiceProvider"

3、更改配置文件,定义过滤机制

return [
    'encoding'      => 'UTF-8',
    'finalize'      => true,
    'cachePath'     => storage_path('app/purifier'),
    'cacheFileMode' => 0755,
    'settings'      => [
        'user_topic_body' => [
            'HTML.Doctype'             => 'XHTML 1.0 Transitional',
            //信任的html元素,
            'HTML.Allowed'             => 'div,b,strong,i,em,a[href|title],ul,ol,ol[start],li,p[style],br,span[style],img[width|height|alt|src],*[style|class],pre,hr,code,h2,h3,h4,h5,h6,blockquote,del,table,thead,tbody,tr,th,td',
            //信任的css属性
            'CSS.AllowedProperties'    => 'font,font-size,font-weight,font-style,margin,width,height,font-family,text-decoration,padding-left,color,background-color,text-align',
            'AutoFormat.AutoParagraph' => true,
            'AutoFormat.RemoveEmpty'   => true,
        ],

    ],

];

4、使用

通过辅助函数clean()来过滤未在白名单里的元素

class TopicObserver
{
    public function saving(Topic $topic)
    {
        $topic->body=clean($topic->body,'user_topic_body');
        $topic->excerpt=make_excerpt($topic->body);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值