萬盛學電腦網

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

PHP 取得完整 URL 與各段資訊的完整方法總覽

$_SERVER 關鍵變數速查

變數說明範例
HTTP_HOST主機名(含港口若非標準)example.com:8080
SERVER_NAME伺服器設定主機名example.com
SERVER_PORT伺服器埠號80 / 443 / 8080
REQUEST_URI完整請求 URI(含查詢字串)/path/to/page.php?id=1&name=test
PHP_SELF當前腳本路徑(相對 DocumentRoot)/path/to/page.php
QUERY_STRING查詢字串(? 之後)id=1&name=test
HTTPS是否為 HTTPS(on/off)on
HTTP_REFERER來源頁面(不可靠,可偽造)https://google.com/

常見組合拼湊完整 URL

1. 簡易版(不含埠號)

<?php
$url = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
// https://example.com/path/page.php?id=1
?>

2. 含埠號版

<?php
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$host   = $_SERVER['HTTP_HOST']; // 已含埠號(若非標準)
$uri    = $_SERVER['REQUEST_URI'];
$url = "$scheme://$host$uri";
?>

3. 手動組裝(最完整控制)

<?php
function getFullUrl(): string {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host   = $_SERVER['HTTP_HOST']; // 若需分離 host:port 可用 SERVER_NAME + SERVER_PORT
    $uri    = $_SERVER['REQUEST_URI'];
    return "$scheme://$host$uri";
}
?>

取得特定部分

只取路徑(不含查詢字串)

<?php
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
// /path/to/page.php
?>

取得目錄路徑

<?php
$fullUrl = getFullUrl();
$dirUrl = dirname($fullUrl); // https://example.com/path
?>

解析 URL 各部件

<?php
$url = 'https://user:pass@example.com:8080/path/page.php?query=1#fragment';
$parts = parse_url($url);
/*
Array
(
    [scheme] => https
    [host] => example.com
    [port] => 8080
    [user] => user
    [pass] => pass
    [path] => /path/page.php
    [query] => query=1
    [fragment] => fragment
)
*/
?>

進階:解析查詢字串為陣列

<?php
$query = $_SERVER['QUERY_STRING']; // id=1&name=test&tags[]=a&tags[]=b
parse_str($query, $params);
/*
$params = [
    'id' => '1',
    'name' => 'test',
    'tags' => ['a', 'b']
]
*/
?>

實用工具函式庫

<?php
class UrlHelper {
    /** 取得完整 URL */
    public static function current(): string {
        $scheme = self::isHttps() ? 'https' : 'http';
        return $scheme . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    }

    /** 判斷是否 HTTPS */
    public static function isHttps(): bool {
        return (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
            || (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] === 443)
            || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https');
    }

    /** 取得基底 URL(不含查詢字串) */
    public static function base(): string {
        $scheme = self::isHttps() ? 'https' : 'http';
        return $scheme . '://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['SCRIPT_NAME']);
    }

    /** 取得當前路徑 */
    public static function path(): string {
        return parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
    }

    /** 取得查詢參數陣列 */
    public static function queryParams(): array {
        $params = [];
        parse_str($_SERVER['QUERY_STRING'] ?? '', $params);
        return $params;
    }

    /** 產生帶新參數的 URL */
    public static function withParams(array $newParams): string {
        $params = array_merge(self::queryParams(), $newParams);
        return self::path() . '?' . http_build_query($params);
    }
}

// 使用範例
echo UrlHelper::current();           // 完整 URL
echo UrlHelper::withParams(['page' => 2, 'sort' => 'desc']); // /path?page=2&sort=desc
?>

反向代理/負載平衡器環境注意事項

  • 真實客戶端 IP:$_SERVER['HTTP_X_FORWARDED_FOR'](取第一個)或 $_SERVER['HTTP_X_REAL_IP']。
  • 真實協定:$_SERVER['HTTP_X_FORWARDED_PROTO'](http/https)。
  • 真實主機:$_SERVER['HTTP_X_FORWARDED_HOST']。
  • 需在 Web Server(Nginx/Apache)正確設定轉發標頭,PHP 端才可信任。

掌握 $_SERVER 變數與 parse_url、parse_str 等函式,能輕鬆處理各種 URL 解析與重建需求。

copyright © 萬盛學電腦網 all rights reserved