HTMLPurifier 是 PHP 專案中標準的 HTML 過濾庫,能有效防止 XSS 攻擊,確保輸出符合標準。本文詳解安裝、配置與進階用法。
下載後核心在 library 目錄,有兩種引入方式:
// 方式一:自動載入器 (官方推薦)
require_once 'HTMLPurifier.auto.php';
$config = HTMLPurifier_Config::createDefault();
// 方式二:手動引入
require_once 'HTMLPurifier.includes.php';
require_once 'HTMLPurifier.autoload.php';
$config = HTMLPurifier_Config::createDefault();
官方配置文檔:configdoc
$config->set('HTML.AllowedElements', ['div'=>true, 'table'=>true, 'tr'=>true, 'td'=>true, 'br'=>true]);
$config->set('HTML.Doctype', 'XHTML 1.0 Transitional'); // 文檔類型
$config->set('Core.Encoding', 'UTF-8'); // 字元編碼
$purifier = new HTMLPurifier($config);
$clean_html = $purifier->purify($dirty_html);
<?php
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('Core.Encoding', 'UTF-8');
$config->set('HTML.Doctype', 'XHTML 1.0 Transitional');
if (!is_null($options)) {
foreach ($options as $option) {
// $option = [directive, value, scope?]
$config->set($option[0], $option[1], $option[2] ?? null);
}
}
$this->_htmlPurifier = new HTMLPurifier($config);
}
public function filter($value) {
return $this->_htmlPurifier->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],
['AutoFormat.RemoveEmpty', true, false],
['AutoFormat.RemoveEmpty.RemoveNbsp', true, false],
['URI.Disable', true, false], // 禁用連結
];
// 使用
$p = new Resume_HtmlPurifier($conf);
$clean_html = $p->filter($html);
| 指令 | 用途 |
|---|---|
| HTML.AllowedElements | 允許的 HTML 標籤白名單 |
| HTML.ForbiddenElements | 禁止的 HTML 標籤黑名單 |
| HTML.AllowedAttributes | 允許的屬性 |
| Attr.EnableID | 是否允許 id 屬性 |
| CSS.AllowedProperties | 允許的 CSS 屬性 |
| URI.AllowedSchemes | 允許的 URL 協定 (http, https, mailto) |
| AutoFormat.AutoParagraph | 自動包裝段落 |
| AutoFormat.RemoveEmpty | 移除空標籤 |
HTMLPurifier_Config 可重複使用,避免重複建立Cache.DefinitionImpl 快取定義檔HTMLPurifier 實例