萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP HTMLPurifier 使用指南:防 XSS、標準化 HTML 輸出

什麼是 HTMLPurifier

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 移除)
?>

進階:自訂過濾器類別 (整合 Zend Filter)

<?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');。

效能提示

  • HTMLPurifier 較重,務必啟用快取 (Cache.SerializerPath)。
  • 大量內容處理建議非同步佇列處理。
  • 若只需簡單標籤剝離,strip_tags() 配合 htmlspecialchars() 輸出端轉義更輕量,但安全性較低。
copyright © 萬盛學電腦網 all rights reserved