HTMLPurifier 是 PHP 最嚴格、標準相容的 HTML 過濾器。它不僅移除惡意標籤/屬性,更能輸出符合 W3C 標準的乾淨 HTML,防止 XSS 攻擊、排版破壞。
composer require ezyang/htmlpurifier
或手動下載 library/HTMLPurifier.auto.php (含自動載入器)。
<?php
require_once 'vendor/autoload.php'; // 或 HTMLPurifier.auto.php
$config = HTMLPurifier_Config::createDefault();
// 允許的標籤 (白名單)
$config->set('HTML.AllowedElements', [
'div' => true, 'span' => true, 'p' => true, 'br' => true,
'strong' => true, 'em' => true, 'ul' => true, 'ol' => true, 'li' => true,
'a' => true, 'img' => true, 'table' => true, 'tr' => true, 'td' => true, 'th' => true,
]);
// 允許的屬性
$config->set('HTML.AllowedAttributes', [
'a.href' => true, 'a.title' => true, 'a.target' => true,
'img.src' => true, 'img.alt' => true, 'img.width' => true, 'img.height' => true,
'*.class' => true, '*.id' => true, '*.style' => true,
]);
// 文件型別
$config->set('HTML.Doctype', 'HTML 4.01 Transitional'); // 或 XHTML 1.0 Transitional
$config->set('Core.Encoding', 'UTF-8');
// 進階:URI 過濾 (防止 javascript: 等危險協定)
$config->set('URI.AllowedSchemes', ['http' => true, 'https' => true, 'mailto' => true]);
// 建立實例
$purifier = new HTMLPurifier($config);
// 淨化
$dirty = '<script>alert(1)</script><p onclick="evil()">Hello<b>World</b></p>';
$clean = $purifier->purify($dirty);
echo $clean;
// 輸出: <p>Hello<b>World</b></p> (script 移除、onclick 移除)
?>
<?php
require_once 'HTMLPurifier.includes.php';
require_once 'HTMLPurifier.autoload.php';
class Resume_HtmlPurifier implements Zend_Filter_Interface {
private $_purifier;
public function __construct(array $options = []) {
$config = HTMLPurifier_Config::createDefault();
$config->set('Core.Encoding', 'UTF-8');
$config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
foreach ($options as $opt) {
// $opt = ['Directive.Name', value, boolean?]
$config->set($opt[0], $opt[1], $opt[2] ?? false);
}
$this->_purifier = new HTMLPurifier($config);
}
public function filter($value) {
return $this->_purifier->purify($value);
}
}
// 使用
$conf = [
['HTML.AllowedElements', ['div'=>true,'table'=>true,'tr'=>true,'td'=>true,'br'=>true], false],
['HTML.AllowedAttributes', ['class'=>true], false],
['Attr.ForbiddenClasses', ['resume_p'=>true], false], // 禁止特定 class
['AutoFormat.RemoveEmpty', true, false],
['AutoFormat.RemoveEmpty.RemoveNbsp', true, false],
['URI.Disable', true, false], // 禁用所有連結
];
$purifier = new Resume_HtmlPurifier($conf);
$cleanHtml = $purifier->filter($userInputHtml);
?>
官方完整配置文件:https://htmlpurifier.org/live/configdoc/plain.html
常用指令:
HTML.AllowedElements、HTML.AllowedAttributes:白名單核心。CSS.AllowedProperties:允許的 CSS 屬性 (如 color, text-align)。Attr.EnableID、Attr.DefaultTextDir 等屬性控制。AutoFormat.AutoParagraph、AutoFormat.RemoveEmpty:自動排版。Cache.SerializerPath:設定快取目錄 (大幅提升效能),$config->set('Cache.SerializerPath', '/tmp/htmlpurifier');。Cache.SerializerPath)。strip_tags() 配合 htmlspecialchars() 輸出端轉義更輕量,但安全性較低。