1、安裝
HTMLPurifier 是基於 PHP 編寫的富文本HTML 過濾器,通常我們可以使用它來防止XSS 跨站攻擊,更多關於 HTMLPurifier的詳情請參考其官網: http://htmlpurifier.org/ 。Purifier 是在Laravel 5 中整合 HTMLPurifier 的擴充包,我們可以通過 Composer 來安裝這個擴充包:
composer require mews/purifier
安裝完成後,在設定檔 config/app.php 的 providers 中註冊HTMLPurifier服務提供者:
'providers' => [ // ... Mews\Purifier\PurifierServiceProvider::class,]
然後在 aliases 中註冊Purifier門面:
'aliases' => [ // ... 'Purifier' => Mews\Purifier\Facades\Purifier::class,]
2、配置
要使用自訂的配置,發行設定檔到 config 目錄:
php artisan vendor:publish
這樣會在 config 目錄下產生一個 purifier.php 檔案:
return [ 'encoding' => 'UTF-8', 'finalize' => true, 'preload' => false, 'cachePath' => null, 'settings' => [ 'default' => [ 'HTML.Doctype' => 'XHTML 1.0 Strict', 'HTML.Allowed' => 'div,b,strong,i,em,a[href|title],ul,ol,li,p[style],br,span[style],img[width|height|alt|src]', 'CSS.AllowedProperties' => 'font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,color,background-color,text-align', 'AutoFormat.AutoParagraph' => true, 'AutoFormat.RemoveEmpty' => true ], 'test' => [ 'Attr.EnableID' => true ], "youtube" => [ "HTML.SafeIframe" => 'true', "URI.SafeIframeRegexp" => "%^(http://|https://|//)(www.youtube.com/embed/|player.vimeo.com/video/)%", ], ],];
3、使用樣本
可以使用輔助函數 clean :
clean(Input::get('inputname'));
或者使用 Purifier 門面提供的 clean 方法:
Purifier::clean(Input::get('inputname'));
還可以在應用中進行動態配置:
clean('This is my H1 title', 'titles');clean('This is my H1 title', array('Attr.EnableID' => true));
或者你也可以使用 Purifier 門面提供的方法:
Purifier::clean('This is my H1 title', 'titles');Purifier::clean('This is my H1 title', array('Attr.EnableID' => true));