HTML 中的 `<`、`>`、`&`、`"`、`'` 為保留字元,**直接輸出使用者輸入或資料庫內容會導致 XSS (跨站腳本攻擊) 或標籤結構破壞**。正確的實體編碼 (Entity Encoding) 是 Web 安全第一道防線。
| 字元 | 實體名稱 | 十進制 | 十六進制 | 說明 |
|---|---|---|---|---|
< | < | < | < | 標籤開始,最危險 |
> | > | > | > | 標籤結束 |
& | & | & | & | 實體起始,**必須最先轉義** |
" | " | " | " | 屬性值雙引號內必轉 |
' | ' / ' / ' | ' | ' | 屬性值單引號內必轉 (HTML5 標準實體) |
{{-- Laravel Blade --}}
{{ $userInput }} {{-- 自動轉義 --!!
{!! $trustedHtml !!} {{-- 輸出原始 HTML (極度危險,僅限極度信任內容) --}}
{# Twig (Symfony/Drupal) #}
{{ userInput }} {# 自動轉義 #}
{{ userInput|raw }} {# 關閉轉義 #}
{% raw %}{% endraw %} {{-- Jinja2 (Flask/Django/Ansible) --}}
{{ userInput }} {# 自動轉義 (需開啟 autoescape) #}
{{ userInput | safe }} {# 關閉轉義 #}
<%= userInput %> <%-- EJS / ERB (Ruby) --%> <%-- 預設輸出原始,需用 <%- userInput %> 轉義 --%>
<%= escapeHtml(userInput) %> <%-- JSP / 早期模板 --%>
**鐵律:除非 100% 確定內容安全 (如後端生成的受信 HTML 片段),否則永遠使用預設自動轉義輸出。**
// 萬用轉義函數 (針對 HTML 內容上下文)
function escapeHtml(unsafe) {
return unsafe
.replaceAll('&', '&') // 必須最先處理 &
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"')
.replaceAll("'", '''); // 或 '
}
// 使用:將字串安全插入元素文字內容
element.textContent = userInput; // **最推薦**:瀏覽器原生 API,完全不解析 HTML,效能最好、最安全
// 若必須用 innerHTML (如富文本編輯器輸出),必須配合 DOMPurify 淨化
import DOMPurify from 'dompurify';
element.innerHTML = DOMPurify.sanitize(userHtml); // 移除 script, onerror, javascript: 等攻擊向量
<!-- 雙引號屬性值 -->
<input value="<script>alert(1)</script>">
<!-- 必須轉義 &, ", <, > -->
<!-- 單引號屬性值 -->
<input value='<script>alert(1)</script>'>
<!-- 必須轉義 &, ', <, > -->
<!-- 無引號屬性值 (極度危險,禁用) -->
<input value=unsafe> <!-- 空格、等號、引號、反引號、`<`、`>` 皆可突破 -->
**最佳實踐:永遠使用雙引號包裹屬性值**,模板引擎自動處理轉義。
// URL 參數值編碼 (百分號編碼 Percent-Encoding)
const url = '/search?q=' + encodeURIComponent(userQuery); // 空格→%20, &→%26, =→%3D...
// URL 路徑段編碼
const path = '/user/' + encodeURIComponent(username); // 保留 / 不編碼
// HTML 內的 URL 屬性:雙重編碼 (先 URL 編碼,再 HTML 實體編碼 & → &)
<a href="/search?q={encodeURIComponent(query)}">搜尋</a>
// 瀏覽器原生解碼 (僅限數字實體)
const txt = document.createElement('textarea');
txt.innerHTML = '<script>';
console.log(txt.value); // "