在 Laravel 5 中使用 Purifier 擴充包整合 HTMLPurifier 防止 XSS 跨站攻擊

來源:互聯網
上載者:User

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));
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.