萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 取得當前完整 URL 的標準與相容做法

標準做法:$_SERVER 變數組合

<?php
/**
 * 取得當前請求的完整 URL (含查詢字串)
 */
function getCurrentUrl(): string {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host   = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? 'localhost';
    $uri    = $_SERVER['REQUEST_URI'] ?? '';
    
    return $scheme . '://' . $host . $uri;
}

/** 取得不含查詢字串的基底 URL */
function getBaseUrl(): string {
    $url = getCurrentUrl();
    $pos = strpos($url, '?');
    return $pos !== false ? substr($url, 0, $pos) : $url;
}

/** 取得網站根目錄 URL */
function getSiteRoot(): string {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host   = $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? 'localhost';
    $script = $_SERVER['SCRIPT_NAME'] ?? '';
    $dir    = dirname($script);
    return $scheme . '://' . $host . rtrim($dir, '/') . '/';
}
?>

各 $_SERVER 變數用途對照

變數含義範例
REQUEST_URI請求 URI (含查詢字串)/article/123?page=2
SCRIPT_NAME當前執行腳本路徑/index.php
PHP_SELF腳本路徑 (相對 DocumentRoot)/index.php
QUERY_STRING查詢字串 (不含 ?)page=2&sort=desc
HTTP_HOSTHost 標頭 (含端口)example.com:8080
SERVER_NAME伺服器設定名稱example.com
HTTPSHTTPS 時為 'on'on
SERVER_PORT伺服器端口443

反向代理/負載平衡器環境修正

若 PHP 位於 Nginx/Cloudflare/ALB 後方,需信任 X-Forwarded-* 標頭:

<?php
function getTrustedScheme(): string {
    // 信任代理標頭 (需確認代理確實設定)
    if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
        $protos = explode(',', $_SERVER['HTTP_X_FORWARDED_PROTO']);
        return trim($protos[0]) === 'https' ? 'https' : 'http';
    }
    return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
}

function getTrustedHost(): string {
    if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
        $hosts = explode(',', $_SERVER['HTTP_X_FORWARDED_HOST']);
        return trim($hosts[0]);
    }
    return $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? 'localhost';
}

function getCurrentUrlTrusted(): string {
    return getTrustedScheme() . '://' . getTrustedHost() . ($_SERVER['REQUEST_URI'] ?? '');
}
?>

Symfony/Laravel 等框架的做法

  • Laravel:request()->fullUrl()、url()->current()、URL::current() (自動處理代理,需設定 TrustedProxies 中介層)。
  • Symfony:$request->getUri()、$request->getSchemeAndHttpHost()。
  • 原生 PSR-7:$request->getUri()->__toString()。

常見陷阱

  • $_SERVER['PHP_SELF'] 易受 XSS 攻擊(表單 action 直接輸出),必須 htmlspecialchars()。
  • 端口 80/443 通常不顯示於 URL,非標準端口需包含。
  • REQUEST_URI 在某些 CGI 模式下可能不包含查詢字串,需回退 QUERY_STRING。

最佳實踐封裝

<?php
class UrlHelper {
    public static function current(): string {
        static $cached = null;
        if ($cached !== null) return $cached;
        
        $scheme = self::detectScheme();
        $host   = self::detectHost();
        $uri    = $_SERVER['REQUEST_URI'] ?? '';
        
        return $cached = $scheme . '://' . $host . $uri;
    }
    
    private static function detectScheme(): string {
        if (isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
            return (explode(',', $_SERVER['HTTP_X_FORWARDED_PROTO'])[0] === 'https') ? 'https' : 'http';
        }
        return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    }
    
    private static function detectHost(): string {
        if (isset($_SERVER['HTTP_X_FORWARDED_HOST'])) {
            return explode(',', $_SERVER['HTTP_X_FORWARDED_HOST'])[0];
        }
        return $_SERVER['HTTP_HOST'] ?? $_SERVER['SERVER_NAME'] ?? 'localhost';
    }
    
    public static function currentWithoutQuery(): string {
        $url = self::current();
        $pos = strpos($url, '?');
        return $pos !== false ? substr($url, 0, $pos) : $url;
    }
}
?>

正確取得當前 URL 是建構分享連結、Canonical 標籤、OAuth 回調、支付通知等功能的基礎,務必處理代理環境與安全輸出。

copyright © 萬盛學電腦網 all rights reserved