1、使用composer执行命令,安装 ezyang/htmlpurifier 扩展类库
项目目录下
composer require ezyang/htmlpurifier
在app/common.php中定义remove_xss函数
if (!function_exists('remove_xss')) {
//使用htmlpurifier防范xss攻击
function remove_xss($string){
//相对index.php入口文件,引入HTMLPurifier.auto.php核心文件
//require_once './plugins/htmlpurifier/HTMLPurifier.auto.php';
// 生成配置对象
$cfg = HTMLPurifier_Config::createDefault();
// 以下就是配置:
$cfg -> set('Core.Encoding', 'UTF-8');
// 设置允许使用的HTML标签
$cfg -> set('HTML.Allowed','div,b,strong,i,em,a[href|title],ul,ol,li,br,p[style],span[style],img[width|height|alt|src]');
// 设置允许出现的CSS样式属性
$cfg -> set('CSS.AllowedProperties', 'font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,color,background-color,text-align');
// 设置a标签上是否允许使用target="_blank"
$cfg -> set('HTML.TargetBlank', TRUE);
// 使用配置生成过滤用的对象
$obj = new HTMLPurifier($cfg);
// 过滤字符串
return $obj -> purify($string);
}
}
第2中方法
namespace app;
class Request extends \think\Request
{
protected $filter = ['htmlspecialchars'];
}
也支持使用Request对象进行全局变量的获取过滤,过滤方式包括函数、方法过滤,以及PHP内置的Types of filters,我们可以设置全局变量过滤方法,支持设置多个过滤方法,例如:
Request::filter(['strip_tags','htmlspecialchars'])
也可以在获取变量的时候添加过滤方法,例如:
Request::get('name','','htmlspecialchars'); // 获取get变量 并用htmlspecialchars函数过滤
Request::param('username','','strip_tags'); // 获取param变量 并用strip_tags函数过滤
Request::post('name','','org\Filter::safeHtml'); // 获取post变量 并用org\Filter类的safeHtml方法过滤
可以支持传入多个过滤规则,例如:
Request::param('username','','strip_tags,strtolower'); // 获取param变量 并依次调用strip_tags、strtolower函数过滤
如果当前不需要进行任何过滤的话,可以使用
// 获取get变量 并且不进行任何过滤 即使设置了全局过滤
Request::get('name', '', null);
普通输入内容,使用转化的思想进行处理。
富文本编辑器内容,使用过滤的思想进行处理。
比如商品描述字段,处理如下:
//商品添加或修改功能中
$params = input();
//单独处理商品描述字段 goods_introduce
$params['goods_desc'] = input('goods_desc', '', 'remove_xss');