首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 使用 get_headers 函數檢測遠程文件是否存在

     編輯:PHP 相關知識

前言

在 PHP 開發中,判斷遠程文件是否存在是常見需求。早期常用 fopen、socket 或 cURL 實現,其實 PHP 內建的 get_headers() 函數也能輕鬆完成這項任務,且代碼更簡潔。本文將詳細介紹 get_headers() 的用法、返回值結構,並提供實用的封裝函數示例。

get_headers() 函數簡介

get_headers() 會向指定 URL 發送 HTTP 請求,並以陣列形式返回伺服器響應的所有標頭資訊。其語法如下:

get_headers(string $url, bool $format = false): array|false
  • $url:目標 URL(必須為字串格式)。
  • $format:可選參數,若設為 true,返回關聯陣列(鍵為標頭名稱);預設為 false,返回索引陣列。

注意:使用此函數需在 php.ini 中開啟 allow_url_fopen = On,否則會報錯。

返回值示例

以 https://www.example.com 為例:

索引陣列(預設)

Array
(
    [0] => HTTP/1.1 200 OK
    [1] => Date: Sat, 29 May 2004 12:28:13 GMT
    [2] => Server: Apache/1.3.27 (Unix) (Red-Hat/Linux)
    [3] => Last-Modified: Wed, 08 Jan 2003 23:11:55 GMT
    [4] => ETag: "3f80f-1b6-3e1cb03b"
    [5] => Accept-Ranges: bytes
    [6] => Content-Length: 438
    [7] => Connection: close
    [8] => Content-Type: text/html
)

關聯陣列($format = true)

Array
(
    [0] => HTTP/1.1 200 OK
    [Date] => Sat, 29 May 2004 12:28:14 GMT
    [Server] => Apache/1.3.27 (Unix) (Red-Hat/Linux)
    [Last-Modified] => Wed, 08 Jan 2003 23:11:55 GMT
    [ETag] => "3f80f-1b6-3e1cb03b"
    [Accept-Ranges] => bytes
    [Content-Length] => 438
    [Connection] => close
    [Content-Type] => text/html
)

封裝函數:判斷遠程文件是否存在

以下函數解析響應狀態碼,若為 2xx 或 3xx(小於 400)則視為文件存在:

function remote_file_exists($url) {
    $executeTime = ini_get('max_execution_time');
    ini_set('max_execution_time', 0); // 移除執行時間限制,防止大文件超時
    $headers = @get_headers($url);
    ini_set('max_execution_time', $executeTime); // 恢復原設定

    if ($headers) {
        $head = explode(' ', $headers[0]);
        // $head[1] 為狀態碼,如 200、301、404 等
        if (!empty($head[1]) && intval($head[1]) < 400) {
            return true;
        }
    }
    return false;
}

關鍵點:

  • 使用 @ 抑制警告(如連接失敗)。
  • 臨時將 max_execution_time 設為 0(無限制),避免大文件或慢速伺服器導致腳本中斷。
  • 判斷依據為 HTTP 狀態碼 < 400(包含 2xx 成功、3xx 重定向)。

進階:排除重定向獲取真實標頭

預設 get_headers() 會自動跟隨重定向(301/302),若需獲取首次響應的原始標頭(不跟隨跳轉),可透過串流上下文控制:

function get_real_headers($url, $format = 0, $follow_redirect = 0) {
    if (!$follow_redirect) {
        // 設定不跟隨重定向、忽略錯誤
        $opts = [
            'http' => [
                'max_redirects' => 1,
                'ignore_errors' => 1
            ]
        ];
        stream_context_set_default($opts);
    }
    $headers = get_headers($url, $format);
    // 恢復預設設定
    if (isset($opts)) {
        $opts = [
            'http' => [
                'max_redirects' => 20,
                'ignore_errors' => 0
            ]
        ];
        stream_context_set_default($opts);
    }
    return $headers;
}

此函數允許開發者選擇是否跟隨重定向,適合需分析跳轉鏈路或檢測短網址真實目標的場景。

總結

get_headers() 是 PHP 內建的輕量級工具,無需額外擴展即可完成遠程文件存在性檢測。結合狀態碼判斷與串流上下文控制,可滿足大多數業務需求。實際專案中建議封裝為工具類,並加入超時、重試等健壯性處理。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved