简介:

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


避免 XSS 攻击

  • 第一种,对用户提交的数据进行过滤
  • 第二种,Web 网页显示时对数据进行特殊处理,一般使用 htmlspecialchars() 输出。


composer安装HTMLPurifier for Laravel 5

  • 安装:

    1. composer require mews/purifier
  • 配置:php artisan vendor:publish –provider=”Mews\Purifier\PurifierServiceProvider”

  • 请将配置信息替换为以下: ``` config/purifier.php

<?php

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, ], ], ];

<a name="CrhE6"></a>
### 模型过滤

- 引入HTMLPurifier 类
- 现在我们只需要在数据入库前(使用 saving 事件)进行过滤即可:
```php
app/Observers/TopicObserver.php

<?php

namespace App\Observers;

use App\Models\Topic;

// creating, created, updating, updated, saving,
// saved,  deleting, deleted, restoring, restored

class TopicObserver
{
    public function saving(Topic $topic)
    {
        $topic->body = clean($topic->body, 'user_topic_body'); 

        $topic->excerpt = make_excerpt($topic->body);
    }
}

or

Purifier::clean(Input::get('inputname'));