在 PHP 開發中,get_headers() 是一個極為實用的系統級函數,它能發送 HTTP 請求並回傳伺服器回應的標頭資訊陣列。若請求失敗則回傳 FALSE 並觸發 E_WARNING 錯誤,這特性常被用來判斷遠端檔案是否存在。
array get_headers ( string $url [, int $format = 0 ] )
Content-Type、Server 等),否則返回數字索引陣列。<?php
$url = 'https://www.example.com';
// 格式 0:數字索引陣列
print_r(get_headers($url));
// 格式 1:關聯陣列(鍵名為標頭欄位)
print_r(get_headers($url, 1));
?>
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
)
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
)
Content-Type、Content-Length、Last-Modified 等,適合做快取驗證或檔案類型偵測。Location 標頭,可追蹤重導向路徑。stream_context_create() 設定 method => 'HEAD'。verify_peer => false(僅測試環境建議)。timeout context 參數。