在 PHP 開發中,精確獲取當前頁面 URL 的各個組成部分是常見需求。$_SERVER 超全域陣列提供了豐富的伺服器與請求資訊,本文系統整理各項關鍵變數用法並提供組合技巧。
假設測試網址:https://localhost/blog/testurl.php?id=5
| 變數 | 輸出範例 | 說明 |
|---|---|---|
HTTP_HOST | localhost | 域名或主機地址(不含埠號) |
PHP_SELF | /blog/testurl.php | 當前腳本路徑(相對 DocumentRoot) |
QUERY_STRING | id=5 | 查詢字串(問號後參數) |
REQUEST_URI | /blog/testurl.php?id=5 | 完整請求 URI(含查詢字串) |
SERVER_NAME | localhost | 伺服器主機名(Apache 需設定 ServerName) |
SERVER_PORT | 80 | 伺服器埠號 |
HTTP_REFERER | (上一頁網址) | 來源頁面(不可靠,用戶可偽造) |
$url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
// 輸出:https://localhost/blog/testurl.php?id=5
$url = 'https://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI'];
// 輸出:https://localhost:80/blog/testurl.php?id=5
$url = 'https://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
echo dirname($url); // https://localhost/blog
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "https://";
$url = $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
// 頂層視窗網址
top.location.href
// 當前視窗網址
this.location.href
// 或
window.location.href
HTTP_REFERER 可被用戶端偽造或攔截,不可用於安全驗證PHP_SELF 存在 XSS 風險(如 /script.php/<script>alert(1)</script>),輸出時務必 htmlspecialchars()HTTP_X_FORWARDED_FOR 或 HTTP_CLIENT_IPfunction getCurrentUrl() {
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'https://';
return $protocol . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}
function getBaseUrl() {
$protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https://' : 'https://';
return $protocol . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']);
}