在 PHP 開發中,常需要驗證遠端 URL 指向的資源是否真實存在。傳統做法多使用 fopen、socket 或 cURL,但其實內建的 get_headers() 函數就能輕鬆完成這項任務,程式碼更簡潔直觀。
get_headers(string $url, bool $associative = false) 會向指定 URL 發送 HEAD 請求,並以陣列形式回傳伺服器響應的 HTTP 標頭。若執行失敗則回傳 false 並觸發 E_WARNING。注意:php.ini 中必須啟用 allow_url_fopen = On 才能使用此函數。
true 時,回傳關聯陣列,鍵名為標頭名稱(如 Content-Type),值為對應內容。<?php
$url = 'https://www.example.com';
print_r(get_headers($url));
print_r(get_headers($url, 1));
?>
執行結果會顯示類似下列的標頭資訊:
Array
(
[0] => HTTP/1.1 200 OK
[1] => Cache-Control: max-age=1800
[Content-Type] => text/html
...
)
以下函數根據回傳的狀態碼判斷檔案是否存在(狀態碼 < 400 視為成功):
<?php
function remote_file_exists($url) {
$original_timeout = ini_get('max_execution_time');
ini_set('max_execution_time', 0); // 移除執行時間限制
$headers = @get_headers($url);
ini_set('max_execution_time', $original_timeout); // 還原設定
if ($headers) {
// 解析第一行:HTTP/1.1 200 OK
$parts = explode(' ', $headers[0]);
if (!empty($parts[1]) && (int)$parts[1] < 400) {
return true;
}
}
return false;
}
?>
預設 get_headers() 會自動追蹤重導向。若需獲取不含重導向的原始標頭,可透過串流上下文設定 max_redirects = 1 與 ignore_errors = 1:
<?php
function get_real_headers($url, $format = 0, $follow_redirect = 0) {
if (!$follow_redirect) {
$opts = [
'http' => [
'max_redirects' => 1,
'ignore_errors' => 1
]
];
stream_context_get_default($opts);
}
$headers = get_headers($url, $format);
// 還原預設串流上下文
$opts = [
'http' => [
'max_redirects' => 20,
'ignore_errors' => 0
]
];
stream_context_get_default($opts);
return $headers;
}
?>
善用 get_headers() 即可快速實現遠端檔案存在性檢查,適合簡單輕量的場景。