PHP 之使用HTMLPurifier过滤XSS
一、HTMLPurifier下载
二、cleanXSS函数封装
function cleanXSS($content) { require_once 'xss/htmlpurifier/library/HTMLPurifier.auto.php'; $config = HTMLPurifier_Config::createDefault(); // 允许的html标签 // $config->set('HTML.Allowed', 'img[src|style],a[href]'); //设置允许的属性 // $config->set('HTML.AllowedAttributes', array('style' => true, 'src' => true)); //允许特定的CSS属性 // $config->set('CSS.AllowedProperties', 'width,height'); //禁止css类名 // $config->set('Attr.ForbiddenClasses', 'test, aa'); $purifier = new HTMLPurifier($config); $clean_html = $purifier->purify($content); return $clean_html; }
三、参数说明
1、只允许特定html标签
$config->set('HTML.Allowed', 'img[src|style],a[href]');
2、只允许html标签属性
$config->set('HTML.AllowedAttributes', array('style' => true, 'src' => true));
3、只允许特定的CSS属性
$config->set('CSS.AllowedProperties', 'width,height');
4、相对路径(/test/a/b)转为绝对路径(https://www.test.com/test/a/b)
$config->set('URI.Base', 'https://www.test.com'); $config->set('URI.MakeAbsolute', true);
更多请查看http://htmlpurifier.org/live/configdoc/plain.html
四、简单示例
过滤前
<img class="aa" src="https://www.test.com/api/avatar/default.jpg?v=1754031794" style="width:100px;" onerror="alert(1)"/><a href="http://www.baidu.com" class="test" onclick="alert('xss')">123</a>
过滤后
<img class="aa" src="https://www.test.com/api/avatar/default.jpg?v=1754031794" style="width:100px;" alt="default.jpg?v=1754031794" /><a href="http://www.baidu.com" class="test">123</a>