整理從 $_SERVER 超全域陣列取得目前頁面 URL 的各種組合方式,包含 HTTP/HTTPS 自動判斷、非標準連接埠處理、路徑提取,並封裝成可重用函數。
| 變數 | 說明 | 範例 |
|---|---|---|
HTTP_HOST | Host Header (含連接埠若非標準) | example.com:8080 |
SERVER_NAME | Server 設定主機名 | example.com |
SERVER_PORT | Server 連接埠 | 80, 443, 8080 |
REQUEST_URI | 請求 URI (含查詢字串) | /path?foo=bar |
PHP_SELF | 當前腳本路徑 | /index.php |
QUERY_STRING | 查詢字串 | foo=bar |
HTTPS | HTTPS 時為 'on' | on / 未設定 |
// 基本版
$url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
// 含 HTTPS 判斷 + 非標準連接埠
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$port = $_SERVER['SERVER_PORT'];
$url = $scheme . '://' . $_SERVER['HTTP_HOST'];
if (($scheme === 'http' && $port !== '80') || ($scheme === 'https' && $port !== '443')) {
$url = $scheme . '://' . $_SERVER['SERVER_NAME'] . ':' . $port . $_SERVER['REQUEST_URI'];
}
// 只取目錄路徑
$dir = dirname('https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
function getCurrentUrl(): string {
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'];
$uri = $_SERVER['REQUEST_URI'];
$port = $_SERVER['SERVER_PORT'];
if (($scheme === 'http' && $port !== '80') || ($scheme === 'https' && $port !== '443')) {
$host = $_SERVER['SERVER_NAME'] . ':' . $port;
}
return $scheme . '://' . $host . $uri;
}
HTTP_HOST 來自 Client Header,**可被偽造**。安全敏感場合 (如產生重設密碼連結) 應使用 SERVER_NAME (需正確設定 Server) 或固定域名常數。htmlspecialchars($url, ENT_QUOTES, 'UTF-8')。X-Forwarded-Proto、X-Forwarded-Host 標頭。