HTML Purifier简介与安装配置使用说明

更新时间:2021-08-04 编辑:未知 关注人次:0 云搜索


在PHP里解决XSS最简单的方法是使用htmlspecialchars转义xml实体,但对于需要使用xml的时候就搏手无策了。之前一直使用一个叫RemoveXSS的函数,该函数过滤得比较严格,很多html特性都过滤了,而且有bug,不修改代码使用起来很不友好,修改了却无法应对灵活的XSS攻击。


HTML Purifier是基于php 5所编写的HTML过滤器,支持自定义过滤规则,还可以把不标准的HTML转换为标准的HTML,是WYSIWYG编辑器的福音。


HTML Purifier可以帮助用户保障HTML的合法性,它可以使你确认HTML是否包含跨站脚本攻击企图或其它的恶意攻击。通过该软件你准许用户粘贴一些HTML内容,却不会让其插入恶意代码,而这种代码可在查看这些HTML的任何人的浏览器中运行。我们可以通过CodeIgniter、 Drupal、 MODx、 Phorum、 Joomla! 、WordPress等来使用该软件。


2、使用HTML Purifier的要求

php 5+

iconv

bcmath

tidy


3、安装配置


3.1下载安装

http://htmlpurifier.org/download

直接下载zip版,把解压后的htmlpurifier中的library拷贝到项目中就可以了。


3.2初始化和设置


require_once ‘htmlpurifier-4.5.0/library/HTMLPurifier.auto.php’; //引用


$config = HTMLPurifier_Config::createDefault();

$config->set(‘HTML.AllowedElements’, array(‘div’=>true, ‘table’=>true, ‘tr’=>true, ‘td’=>true, ‘br’=>true)); //允许属性 div table tr td br元素

$config->set(‘HTML.Doctype’, ‘XHTML 1.0 Transitional’) //html文档类型

$config->set(‘Core.Encoding’, ‘UTF-8’) //字符编码


4、调用并使用


$purifier = new HTMLPurifier($config); //new一个

$puri_html = $purifier->purify($html); //搞定~!


阿里云-推广AD

5、看了其他攻略中,有一个新建一个类的使用方法,也不错,粘过来


require_once ‘htmlpurifier-4.5.0/library/HTMLPurifier.auto.php’;


class Resume_HtmlPurifier

{

protected $_htmlPurifier = null;


public function __construct($options = null)

{

$config = HTMLPurifier_Config::createDefault();

$config->set(‘Core.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 = array(

array(‘HTML.AllowedElements’,

array(

‘div’ => true,

‘table’ => true,

‘tr’ => true,

‘td’ => true,

‘br’ => true,

‘img’=> true

),

false), //允许属性 div table tr td br img元素


/* 以下几行注释去掉,过滤将变得非常严格,通常情况无需使用: */

//    array(‘HTML.AllowedAttributes’, array(‘class’ => TRUE), false), //允许属性 class

//    array(‘Attr.ForbiddenClasses’, array(‘resume_p’ => TRUE), false), //禁止classes如

//    array(‘AutoFormat.RemoveEmpty’, true, false), //去空格

//    array(‘AutoFormat.RemoveEmpty.RemoveNbsp’, true, false), //去nbsp

//    array(‘URI.Disable’, true, false),

);


$p = new Resume_HtmlPurifier($conf);

$puri_html = $p->filter($html);


6、XSS攻击示范代码


‘>



link


本文地址: http://www.4435.cn/a/xinwenguandian/jianzhanzhishi/2021/0804/32444.html ,转载请注明出处。

服务支持

我们珍惜您每一次在线询盘,有问必答,用专业的态度,贴心的服务。

让您真正感受到我们的与众不同!