多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
安装 ``` composer require ezyang/htmlpurifier ``` 调用 ``` function removeXSS($dirty_html){ require '../vendor/autoload.php'; //或者 //require_once 'library/HTMLPurifier.includes.php'; // 载入核心文件 // 生成配置对象 配置文档http://htmlpurifier.org/live/configdoc/plain.html $config = HTMLPurifier_Config::createDefault(); //设置字符集编码 $config->set('Core.Encoding', 'UTF-8'); /** * 设置文档类型,支持的文档类型包括: * HTML 4.01 Strict * HTML 4.01 Transitional * XHTML 1.0 Strict * XHTML 1.0 Transitional * XHTML 1.1 */ $config->set('HTML.Doctype', 'HTML 4.01 Transitional'); //将相对URL 转换为绝对URL $config->set('URI.Base', 'http://www.example.com'); $config->set('URI.MakeAbsolute', true); //自动分段输入文本 $config->set('AutoFormat.AutoParagraph', true); // // // $config->set('HTML.Allowed', 'p,b,a[href],i'); //设置允许使用的HTML标签 $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]'); // 设置允许出现的CSS样式属性 $config->set('CSS.AllowedProperties', 'font,font-size,font-weight,font-style,font-family,text-decoration,padding-left,color,background-color,text-align'); // 设置a标签上是否允许使用target="_blank" $config->set('HTML.TargetBlank', TRUE); //缓存 //确保Serializer目录拥有存储权限 //chmod -R 0775 HTMLPurifier/DefinitionCache/Serializer //禁用缓存 这会导致性能下降 //$ config-> set('Core.DefinitionCache',null); //将缓存文件移至其他目录 //$config->set('Cache.SerializerPath', '/home/user/absolute/path'); // // // // // // 使用配置生成过滤用的对象 $purifier = new HTMLPurifier($config); // 过滤字符串 $clean_html = $purifier->purify($dirty_html); return $clean_html; } ``` 例子2: ``` require_once 'HTMLPurifier.includes.php'; require_once 'HTMLPurifier.autoload.php'; class Resume_HtmlPurifier implements Zend_Filter_Interface{ protected $_htmlPurifier = null; public function __construct($options = null) { $config = HTMLPurifier_Config::createDefault(); $config->set('Code.Encoding', 'UTF-8'); $config->set('HTML.Doctype', 'XHTML 1.0 Transitional'); if(!is_null($options)){ foreach($options as $option){ $config->set($option[0], $option[1], $option[2]); } } $this->_htmlPurifier = new HTMLPurifier($config); } public function filter($value) { return $this->_htmlPurifier->purify($value); } } $conf=[ //允许属性 div table tr td br元素 [ 'HTML.AllowedElements', [ 'div' => true, 'table' => true, 'tr' => true, 'td' => true, 'br' => true, ], false ], //允许属性 class [ 'HTML.AllowedAttributes', [ 'class' => TRUE ], false ], //禁止classes如 [ 'Attr.ForbiddenClasses', [ 'resume_p' => TRUE ], false ], //去空格 ['AutoFormat.RemoveEmpty', true, false], //去nbsp ['AutoFormat.RemoveEmpty.RemoveNbsp', true, false], ['URI.Disable', true, false], ]; $p = new Resume_HtmlPurifier($conf); $puri_html = $p->filter($html); ```