XSS(Cross-Site Scripting)是 Web 應用最常見的安全漏洞之一。攻擊者透過注入惡意腳本,竊取使用者 Cookie、Session、鍵盤輸入,甚至控制瀏覽器行為。本文說明 XSS 原理、PHP 常見防禦函數、編碼陷阱與一個完整的過濾函數範例。
<script>、onerror、javascript: 等的惡意連結或表單資料。<?php
$str = 'A quote is <b>bold</b>';
echo htmlentities($str); // A quote is <b>bold</b>
echo htmlentities($str, ENT_QUOTES); // A 'quote' is <b>bold</b>
?>
htmlentities($str, ENT_QUOTES, 'UTF-8')。僅轉換 & " ' < > 五個特殊字元,效能優於 htmlentities(),適用於大多數 HTML 輸出場景。
function RemoveXSS($val) {
// 1. 移除不可列印控制字元(保留 CR、LF、TAB)
$val = preg_replace('/([\x00-\x08][\x0b-\x0c][\x0e-\x20])/', '', $val);
// 2. 解碼 HTML 實體與十六進位編碼,防止雙重編碼繞過
$search = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()~`";:?+/={}[]-_|\';
for ($i = 0; $i < strlen($search); $i++) {
$val = preg_replace('/([x|X]0{0,8}' . dechex(ord($search[$i])) . ';?)/i', $search[$i], $val);
$val = preg_replace('/({0,8}' . ord($search[$i]) . ';?)/', $search[$i], $val);
}
// 3. 過濾危險標籤與事件處理器
$ra1 = ['javascript','vbscript','expression','applet','meta','xml','blink','link','style','script','embed','object','iframe','frame','frameset','ilayer','layer','bgsound','title','base'];
$ra2 = ['onabort','onactivate','onafterprint','onafterupdate','onbeforeactivate','onbeforecopy','onbeforecut','onbeforedeactivate','onbeforeeditfocus','onbeforepaste','onbeforeprint','onbeforeunload','onbeforeupdate','onblur','onbounce','oncellchange','onchange','onclick','oncontextmenu','oncontrolselect','oncopy','oncut','ondataavailable','ondatasetchanged','ondatasetcomplete','ondblclick','ondeactivate','ondrag','ondragend','ondragenter','ondragleave','ondragover','ondragstart', /* ...更多事件... */];
$val = str_ireplace($ra1, '', $val);
$val = str_ireplace($ra2, '', $val);
return $val;
}
session.cookie_httponly=1、session.cookie_secure=1(HTTPS 環境)。Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.cdn.com;