透過 URL 傳遞參數時,若參數值包含換行符(URL 編碼為 %0A),直接在 JavaScript 或 PHP 中接收並賦值給變數,可能導致語法錯誤或邏輯異常。例如:
// PHP 產生的 JS 程式碼
var param = "第一行
第二行"; // JS 語法錯誤:字串未閉合
在送出請求前對參數值進行 URL 編碼,接收端再解碼還原,即可避免特殊字元破壞語法結構。
<?php
// 送出端:編碼
$rawValue = "包含\n換行\r\n和特殊字元&符號";
$encoded = urlencode($rawValue);
// 產生連結
echo "<a href='target.php?data=$encoded'>跳轉</a>";
// 接收端:解碼
$decoded = urldecode($_GET['data'] ?? '');
?>
<script>
// 送出端:編碼
const raw = "包含\n換行\n和特殊字元&符號";
const encoded = encodeURIComponent(raw); // 推薦用 encodeURIComponent
// location.href = `target.php?data=${encoded}`;
// 接收端:解碼
const decoded = decodeURIComponent(encoded);
console.log(decoded); // 還原原始字串
</script>
| 語言 | 編碼 | 解碼 | 備註 |
|---|---|---|---|
| PHP | urlencode() | urldecode() | 空格編為 +,符合 application/x-www-form-urlencoded |
| PHP | rawurlencode() | rawurldecode() | 空格編為 %20,符合 RFC 3986,建議一般用途用此 |
| JavaScript | encodeURIComponent() | decodeURIComponent() | 元件編碼,適合查詢字串參數值 |
| JavaScript | encodeURI() | decodeURI() | 整體 URL 編碼,不編碼 :/?#[]@ 等保留字元 |
rawurlencode(),JS 用 decodeURIComponent()。encodeURIComponent(),PHP 用 urldecode() 或自動解碼($_GET/$_POST 已自動解碼)。htmlspecialchars, json_encode, urlencode)。$_GET 會保留 %0A —— PHP 已自動 urldecode,拿到的是真正的換行字元。encodeURI() 編碼參數值 —— 會保留 & = 等字元,導致參數切割錯誤,必須用 encodeURIComponent()。