htmlpurifier的使用

什么是htmlpurifier??

HTML Purifier是一个可以用来移除所有恶意代码(XSS),而且还能确保你的页面遵循W3C的标准规范的PHP类库。
在php里解决XSS最简单的方法是使用htmlspecialchars转义xml实体,但对于需要使用xml的时候就搏手无策了。之前一直使用一个叫RemoveXSS的函数,该函数过滤得比较严格,很多html特性都过滤了,而且有bug,不修改代码使用起来很不友好,修改了却无法应对灵活的XSS攻击。
HTML Purifier是基于php 5所编写的HTML过滤器,支持自定义过滤规则,还可以把不标准的HTML转换为标准的HTML,是WYSIWYG编辑器的福音。

如何使用??

<?php
// 有选择性的过滤XSS --》 说明:性能非常低-》尽量少用
function removeXSS($data)
{
	require_once './HtmlPurifier/HTMLPurifier.auto.php';
	$_clean_xss_config = HTMLPurifier_Config::createDefault();
	$_clean_xss_config->set('Core.Encoding', 'UTF-8');
	// 设置保留的标签
	$_clean_xss_config->set('HTML.Allowed','div,b,strong,i,em,a[href|title],ul,ol,li,p[style],br,span[style],img[width|height|alt|src]');
	$_clean_xss_config->set('CSS.AllowedProperties', 'font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,color,background-color,text-align');
	$_clean_xss_config->set('HTML.TargetBlank', TRUE);
	$_clean_xss_obj = new HTMLPurifier($_clean_xss_config);
	// 执行过滤
	return $_clean_xss_obj->purify($data);
}

 直接调用removeXSS()方法即可

原文地址:https://www.cnblogs.com/ganwenjun/p/6915892.html