HTMLPurifier 是基于 PHP 编写的富文本 HTML 过滤器,通常我们可以使用它来防止 XSS 跨站攻击。
针对XSS跨站攻击,一般有两种方法避免
- 对用户提交的数据进行过滤
- 对显示数据进行特殊处理,一般用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);
}
}