在 PHP 中處理使用者輸入的 HTML 內容時,必須過濾或淨化標籤以防止 XSS 攻擊並確保輸出安全。本文詳細比較三種主流方案:內建 `strip_tags()`、自訂正則表達式、專業庫 HTMLPurifier,分析其優缺點、適用場景與安全性,並提供最佳實踐程式碼範例。
<?php
$html = '<p>內容</p><script>alert(1)</script><b>粗體</b>';
// 1. 移除所有標籤
echo strip_tags($html);
// 輸出:內容alert(1)粗體
// 2. 允許特定標籤 (第二參數)
echo strip_tags($html, '<p><b><i>');
// 輸出:<p>內容</p>alert(1)<b>粗體</b>
// 3. 允許標籤+屬性 (PHP 8.3+ 支援屬性過濾)
echo strip_tags($html, ['p' => ['class'], 'b' => []]);
// 輸出:<p>內容</p>alert(1)<b>粗體</b>
?>
| 優點 | 缺點/風險 |
|---|---|
| 內建函式,零依賴、效能極佳 | **無法防禦屬性型 XSS**:` |
| 語法簡單,適合單純移除標籤 | **不解析巢狀/破損 HTML**,可能殘留不完整標籤 |
| PHP 8.3+ 開始支援屬性白名單 | 無法處理 CSS `expression()`、`javascript:` 協定等進階攻擊向量 |
| 編碼問題:需確保字串為 UTF-8,否則多位元組字元可能被誤傷 |
<?php
$html = '<p>正常</p><script>evil()</script><img src=x onerror=alert(1)>';
// 移除 script 標籤及內容 (不區分大小寫、跨行)
$html = preg_replace('@<script[^>]*>.*?</script>@is', '', $html);
// 移除所有標籤 (極度危險,易誤傷內容)
$html = preg_replace('@<[^>]+>@', '', $html);
// 僅保留白名單標籤 (極其複雜,不建議手寫)
$allowed = ['p', 'b', 'i', 'strong', 'em', 'br'];
$pattern = '@<(/?)([a-zA-Z0-9]+)([^>]*)>@';
$html = preg_replace_callback($pattern, function($m) use ($allowed) {
$tag = strtolower($m[2]);
if (in_array($tag, $allowed)) {
return $m[0]; // 保留
}
return ''; // 移除
}, $html);
?>
⚠️ **生產環境嚴禁使用正則過濾 HTML**,除非極簡單、可控輸入且經過嚴格滲透測試。
composer require ezyang/htmlpurifier
<?php
require_once 'vendor/autoload.php';
$config = HTMLPurifier_Config::createDefault();
// 核心設定
$config->set('HTML.Doctype', 'HTML5');
$config->set('HTML.Allowed', 'p,b,i,strong,em,br,ul,ol,li,a[href|title],img[src|alt|width|height],table,thead,tbody,tr,th,td,caption');
$config->set('CSS.AllowedProperties', 'font,font-size,font-weight,font-style,font-family,text-align,color,background-color,border,margin,padding');
$config->set('AutoFormat.RemoveEmpty', true);
$config->set('AutoFormat.RemoveEmpty.RemoveNbsp', true);
// 安全設定
$config->set('HTML.SafeIframe', false);
$config->set('HTML.SafeObject', false);
$config->set('URI.SafeIframeRegexp', '%^$'); // 禁用 iframe
$purifier = new HTMLPurifier($config);
$dirtyHtml = '<p>正常</p><script>alert(1)</script><img src=x onerror=alert(1)><a href="javascript:alert(1)">連結</a>';
$cleanHtml = $purifier->purify($dirtyHtml);
echo $cleanHtml;
// 輸出:<p>正常</p><img src="x" alt="" /><a href="#">連結</a>
// script 移除、onerror 移除、javascript: 協定移除、img 強制補 alt
?>
$config = HTMLPurifier_Config::createDefault();
// 允許 YouTube iframe
$config->set('HTML.SafeIframe', true);
$config->set('URI.SafeIframeRegexp', '%^(https?:)?//(www\.)?youtube\.com/embed/%');
// 允許 style 屬性 (需 CSS.AllowedProperties)
$config->set('HTML.Allowed', 'div[style],span[style],p[style]');
$config->set('CSS.AllowedProperties', 'color,background-color,font-size,font-weight,text-align,margin,padding,display,flex,grid');
// 快取機制 (生產環境必開)
$config->set('Cache.SerializerPath', '/path/to/writable/cache');
// 自訂元素/屬性 (擴充 HTMLDefinition)
$def = $config->getHTMLDefinition(true);
$def->addElement('my-custom', 'Inline', 'Flow', 'Common', ['data-id' => 'Text']);
$config->set('HTML.DefinitionID', 'custom-v1');
$config->set('HTML.DefinitionRev', 1);
| 維度 | strip_tags() | 正則表達式 | HTMLPurifier |
|---|---|---|---|
| 安全性 (XSS 防禦) | 低 (無屬性過濾) | 極低 (極易繞過) | **極高** (白名單機制、標準解析器) |
| HTML 解析正確性 | 中 (不處理巢狀/破損) | 低 (正則非解析器) | **高** (基於 lexer/parser) |
| 效能 | **極快** (C 實作) | 快 (但長字串風險) | 中等 (需快取加速) |
| 配置彈性 | 低 (僅標籤白名單) | 高 (但維護地獄) | **極高** (完整規則引擎) |
| 學習曲線 | 極低 | 中 (正則本身複雜) | 中 (配置選項多) |
| 適用場景 | 單純移除所有標籤、受信內容簡單清理 | 極受控環境、極簡單規則、原型驗證 | **所有使用者生成內容 (UGC)、CMS、評論、郵件模板、API 輸出** |
PHP 過濾 HTML 標籤,**生產環境請直接使用 HTMLPurifier**。`strip_tags()` 僅適合極簡單、受信任的內容清理;正則表達式處理 HTML 屬於反模式,極高風險。建立專案統一的 `HtmlSanitizer` 服務類,封裝 HTMLPurifier 配置,提供 `sanitize($html, 'profile'/'comment'/'email')` 等場景化方法,確保安全性與一致性。總結