若直接 echo $userInput,惡意使用者可注入 JavaScript(XSS)、破壞 HTML 結構、竊取 Cookie、發起 CSRF 攻擊。例如:
<script>alert('XSS')</script>
<img src=x onerror=stealCookie()>
<?php
echo htmlspecialchars($userInput, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
// < → < > → > " → " ' → ' & → &
?>
允許使用者使用受限、安全的標記,伺服端解析轉換為安全 HTML。
<?php
function parseBBCode(string $text): string
{
// 1. 先全域轉義,徹底中和所有 HTML
$text = htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
// 2. 定義允許的標記對應規則(搜尋 → 替換)
$patterns = [
// [b]粗體[/b]
'/\[b\](.*?)\[\/b\]/s' => '<strong>$1</strong>',
// [i]斜體[/i]
'/\[i\](.*?)\[\/i\]/s' => '<em>$1</em>',
// [u]底線[/u]
'/\[u\](.*?)\[\/u\]/s' => '<u>$1</u>',
// [url]連結[/url] 或 [url=網址]文字[/url]
'/\[url\](.*?)\[\/url\]/s' => '<a href="$1" rel="nofollow ugc">$1</a>',
'/\[url=(.*?)\](.*?)\[\/url\]/s' => '<a href="$1" rel="nofollow ugc">$2</a>',
// [img]圖片網址[/img]
'/\[img\](.*?)\[\/img\]/s' => '<img src="$1" alt="" loading="lazy">',
// [code]程式碼[/code]
'/\[code\](.*?)\[\/code\]/s' => '<pre><code>$1</code></pre>',
// 換行
'/\r?\n/' => '<br>',
];
foreach ($patterns as $pattern => $replacement) {
$text = preg_replace($pattern, $replacement, $text);
}
return $text;
}
?>
jbbcode/jbbcode 等 Composer 套件。若業務必須允許部分 HTML(如富文本編輯器輸出),務必使用 HTMLPurifier,手寫 strip_tags 或 preg_replace 絕對不安全(繞過手法極多:事件屬性、CSS expression、編碼繞過、巢狀標籤...)。
<?php
require_once 'vendor/autoload.php'; // composer require ezyang/htmlpurifier
$config = HTMLPurifier_Config::createDefault();
// 自訂允許標籤
$config->set('HTML.Allowed', 'p,b,i,u,em,strong,a[href|title],ul,ol,li,br,img[src|alt|width|height]');
$config->set('CSS.AllowedProperties', ['font-weight', 'font-style', 'text-decoration']);
$config->set('URI.AllowedSchemes', ['http' => true, 'https' => true, 'mailto' => true]);
$purifier = new HTMLPurifier($config);
$safeHtml = $purifier->purify($userHtmlInput);
?>
| 情境 | 策略 | 關鍵函數/工具 |
|---|---|---|
| HTML 屬性值 | htmlspecialchars(..., ENT_QUOTES) | htmlspecialchars |
| URL 參數 | urlencode | urlencode, http_build_query |
| JavaScript 字串/JSON | json_encode (自動處理引號、換行、Unicode) | json_encode |
| CSS 值 | cssesc 或 白名單驗證 | 避免直接輸出使用者輸入至 CSS |
| SQL 查詢 | 參數化查詢 / 預處理語句 | PDO::prepare, mysqli_stmt |
| Shell 命令 | escapeshellarg / escapeshellcmd | escapeshellarg |
「輸出時過濾,依情境編碼」是防禦 XSS 的鐵律。現代開發應:
htmlspecialchars(模板引擎通常內建自動逃逸)。