查詢

get_headers()函式—用法及示例

「 傳送一個 HTTP 請求並返回響應的頭資訊 」


函式名稱:get_headers()

適用版本:PHP 4 >= 4.0.4, PHP 5, PHP 7

函式描述:get_headers() 函式傳送一個 HTTP 請求並返回響應的頭資訊。

用法: get_headers ( string $url [, int $format = 0 [, resource $context ]] ) : array|false

引數:

  • url: 必需,指定要傳送請求的 URL。
  • format: 可選,指定返回的頭資訊的格式。預設為 0,返回一個關聯陣列。如果設定為 1,將返回一個索引陣列。
  • context: 可選,指定一個上下文資源,用於傳送請求。

返回值:

  • 如果請求成功,將返回一個包含所有響應頭資訊的陣列。
  • 如果請求失敗,則返回 false。

示例: <?php $url = "https://www.example.com"; $headers = get_headers($url);

if ($headers) { foreach ($headers as $header) { echo $header . "
"; } } else { echo "Failed to get headers"; } ?>

輸出: HTTP/1.1 200 OK Date: Mon, 01 Jan 2022 12:00:00 GMT Server: Apache/2.4.38 (Unix) Content-Type: text/html; charset=UTF-8 Content-Length: 1234 ...

注意事項:

  • 該函式依賴於 PHP 的配置和伺服器環境,某些伺服器可能不支援該函式。
  • 在某些情況下,可能無法獲取到全部頭資訊,具體取決於伺服器的配置。
  • 可以透過設定 format 引數為 1 來獲取一個索引陣列形式的頭資訊。
補充糾錯
下一個函式: get_extension_funcs()函式
熱門PHP函式
分享連結