本文實例講述了Laravel5中防止XSS跨站攻擊的方法。小編分享給大家供大家參考,具體如下:
Laravel 5本身沒有這個能力來防止xss跨站攻擊了,但是這它可以使用Purifier 擴展包集成 HTMLPurifier 防止 XSS 跨站攻擊。
1、安裝
HTMLPurifier 是基于 PHP 編寫的富文本 HTML 過濾器,通常我們可以使用它來防止 XSS 跨站攻擊,更多關于 HTMLPurifier的詳情請參考其官網:http://htmlpurifier.org/。Purifier 是在 Laravel 5 中集成 HTMLPurifier 的擴展包,我們可以通過 Composer 來安裝這個擴展包:
composer require mews/purifier
安裝完成后,在配置文件config/app.php的providers中注冊HTMLPurifier服務提供者:
- 'providers' => [
- // ...
- MewsPurifierPurifierServiceProvider::class,
- ]
然后在aliases中注冊Purifier門面:
- 'aliases' => [
- // ...
- 'Purifier' => MewsPurifierFacadesPurifier::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));
php防止xss攻擊
- <?PHP
- function clean_xss(&$string, $low = False)
- {
- if (! is_array ( $string ))
- {
- $string = trim ( $string );
- $string = strip_tags ( $string );
- $string = htmlspecialchars ( $string );
- if ($low)
- {
- return True;
- }
- $string = str_replace ( array ('"', "//", "'", "/", "..", "../", "./", "//" ), '', $string );
- $no = '/%0[0-8bcef]/';
- $string = preg_replace ( $no, '', $string );
- $no = '/%1[0-9a-f]/';
- $string = preg_replace ( $no, '', $string );
- $no = '/[/x00-/x08/x0B/x0C/x0E-/x1F/x7F]+/S';
- $string = preg_replace ( $no, '', $string );
- return True;
- }
- $keys = array_keys ( $string );
- foreach ( $keys as $key )
- { //Vevb.com
- clean_xss ( $string [$key] );
- }
- }
- //just a test
- $str = 'Vevb.com<meta http-equiv="refresh" content="0;">';
- clean_xss($str); //如果你把這個注釋掉,你就知道xss攻擊的厲害了
- echo $str;
- ?>
新聞熱點
疑難解答