萬盛學電腦網

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

PHP 取得遠端伺服器回應標頭資訊:fopen + http_response_header 實戰技巧

一行代碼獲取 HTTP 回應標頭

PHP 內建變數 `$http_response_header` 在使用 `fopen()`、`file_get_contents()` 等串流函式開啟 HTTP/HTTPS URL 後,會自動填入伺服器回應的標頭陣列。無需 cURL 即可快速檢測遠端資源資訊。

基本用法

<?php
$url = 'https://www.example.com/';
$handle = @fopen($url, 'r'); // @ 抑制警告,自行檢查回傳值

if ($handle) {
    echo "<h3>HTTP 回應標頭:</h3><pre>";
    foreach ($http_response_header as $header) {
        echo htmlspecialchars($header) . "\n";
    }
    echo "</pre>";
    fclose($handle);
} else {
    echo "無法開啟連線:{$url}";
}

可獲得的關鍵資訊

標頭用途
HTTP/1.1 200 OK狀態碼,判斷資源是否存在、重導向、錯誤
Server: nginx/1.24.0伺服器軟體與版本
Content-Type: text/html; charset=utf-8MIME 類型與編碼
Content-Length: 1256回應內容長度(位元組)
Last-Modified: Wed, 15 May 2024 10:30:00 GMT資源最後修改時間,可用於快取驗證
ETag: "abc123"實體標籤,條件請求依據
Set-Cookie: session=abc; HttpOnly; SecureCookie 設定,含安全屬性
X-Powered-By: PHP/8.2.10後端技術棧洩露(建議隱藏)
Content-Security-Policy: ...CSP 政策

進階應用場景

1. 檢測遠端檔案是否存在(不下載內容)

<?php
function remoteFileExists(string $url): bool
{
    $handle = @fopen($url, 'r');
    if (!$handle) return false;

    // 僅讀取標頭,關閉連線
    fclose($handle);

    // 解析狀態行
    $statusLine = $http_response_header[0] ?? '';
    return (bool)preg_match('/^HTTP\/\d\.\d\s+2\d\d/', $statusLine);
}

var_dump(remoteFileExists('https://www.php.net/images/logos/php-logo.svg')); // true
var_dump(remoteFileExists('https://www.php.net/not-exist.xyz')); // false

2. 取得遠端檔案大小(不下載)

<?php
function getRemoteFileSize(string $url): ?int
{
    $handle = @fopen($url, 'r');
    if (!$handle) return null;
    fclose($handle);

    foreach ($http_response_header as $header) {
        if (stripos($header, 'Content-Length:') === 0) {
            return (int)trim(substr($header, strlen('Content-Length:')));
        }
    }
    return null; // 可能為分塊傳輸編碼
}

3. 偵測伺服器技術棧(被動指紋識別)

<?php
function detectServerStack(string $url): array
{
    $info = ['server' => 'Unknown', 'powered_by' => 'Unknown', 'cms' => 'Unknown'];
    @fopen($url, 'r');
    foreach ($http_response_header as $h) {
        if (stripos($h, 'Server:') === 0) {
            $info['server'] = trim(substr($h, 7));
        } elseif (stripos($h, 'X-Powered-By:') === 0) {
            $info['powered_by'] = trim(substr($h, 13));
        } elseif (stripos($h, 'X-Generator:') === 0) {
            $info['cms'] = trim(substr($h, 12));
        }
    }
    return $info;
}

限制與注意事項

  • 需開啟 allow_url_fopen:`php.ini` 設定 `allow_url_fopen = On`(預設開啟)。
  • 無法自訂請求標頭:無法發送自定 User-Agent、Authorization、Cookie 等。需完整控制請改用 cURL 或 Guzzle。
  • 不支援 HTTPS 驗證控制:預設驗證 SSL 憑證,若目標憑證無效會失敗。cURL 可設定 `CURLOPT_SSL_VERIFYPEER`。
  • 無法處理重導向細節:會自動追蹤 Location 重導向,但無法取得中間回應、限制重導向次數。
  • 超時控制:受 `default_socket_timeout` (預設 60 秒) 控制,可用 `stream_context_create()` 調整。

更強大的替代方案:cURL / Guzzle

<?php
// cURL 完整控制版
function fetchHeadersCurl(string $url): array
{
    $ch = curl_init($url);
    curl_setopt_array($ch, [
        CURLOPT_NOBODY        => true,      // HEAD 請求
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_MAXREDIRS     => 5,
        CURLOPT_TIMEOUT       => 10,
        CURLOPT_SSL_VERIFYPEER => true,
        CURLOPT_USERAGENT     => 'MyBot/1.0 (+https://mysite.com/bot)',
    ]);
    curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);
    return $info;
}

結語

`$http_response_header` 是 PHP 隱藏的小寶藏,適合快速檢測、簡單監控、教學示範。生產環境需要完整 HTTP 客戶端功能(認證、重試、並發、異步)時,請改用 **Guzzle** 或 **Symfony HttpClient**,擁有更豐富的功能與更好的錯誤處理。

copyright © 萬盛學電腦網 all rights reserved