本文实例讲述了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-x08x0bx0cx0e-x1fx7f]+/s';
$string = preg_replace ( $no, '', $string );
return true;
}
$keys = array_keys ( $string );
foreach ( $keys as $key )
{
clean_xss ( $string [$key] );
}
}
//just a test
$str = 'jb51.net<meta http-equiv="refresh" content="0;">';
clean_xss($str); //如果你把这个注释掉,你就知道xss攻击的厉害了
echo $str;
?>
更多关于laravel相关内容感兴趣的读者可查看本站专题:《laravel框架入门与进阶教程》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php日期与时间用法总结》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于laravel框架的php程序设计有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!