<?php
/**
* 獲取當前訪問的完整 URL
* @return string 完整 URL
*/
function get_current_url() {
$current_url = 'https://';
// 判斷 HTTPS
if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
$current_url = 'https://';
}
// 判斷非標準端口
if ($_SERVER['SERVER_PORT'] != '80') {
$current_url .= $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . $_SERVER['REQUEST_URI'];
} else {
$current_url .= $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
}
return $current_url;
}
?>
| 變量 | 說明 | 示例 |
|---|---|---|
| HTTPS | HTTPS 請求時為 'on' | on |
| SERVER_NAME | 伺服器主機名 | www.example.com |
| SERVER_PORT | 伺服器端口 | 80, 443, 8080 |
| REQUEST_URI | 請求 URI(含查詢字串) | /path/page?param=value |
echo get_current_url();
// 輸出示例:
// https://www.example.com/path/page?param=value
// https://www.example.com:8443/path/page?param=value
function get_current_url_advanced() {
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'];
$uri = $_SERVER['REQUEST_URI'] ?? '';
// 處理代理/負載均衡器傳遞的原始協議
if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
$scheme = $_SERVER['HTTP_X_FORWARDED_PROTO'];
}
return $scheme . '://' . $host . $uri;
}
此函數簡潔可靠,可直接納入專案公共函數庫。