PHP file_get_contents関数のレスポンスヘッダーを取得するには?

ショコラ
ショコラ

PHP file_get_contents関数のレスポンスヘッダーを取得するには?

file_get_contetns関数を実行すると、$http_response_header の変数にレスポンスヘッダーが自動でセットされるので、こちらを使います。
関数から出てしまうと、$http_response_header にはアクセスできないです。

もっさん先輩
もっさん先輩

レスポンスヘッダーをみてみましょう。

<?php
$http_response_header = []; //初期化します。
file_get_contents("https://www.yahoo.co.jp");
var_dump( $http_response_header );

↓こちらが生の実行結果です。

# php a.php
array(19) {
  [0]=>
  string(15) "HTTP/1.1 200 OK"
  [1]=>
  string(11) "Server: ATS"
  [2]=>
  string(35) "Date: Thu, 11 May 2023 10:05:44 GMT"
  [3]=>
  string(38) "Content-Type: text/html; charset=UTF-8"
  [4]=>
  string(19) "Accept-Ranges: none"
  [5]=>
  string(59) "Cache-Control: private, no-cache, no-store, must-revalidate"
  [6]=>
  string(11) "Expires: -1"
  [7]=>
  string(16) "Pragma: no-cache"
  [8]=>
  string(112) "Set-Cookie: B=1t5ur6ti5pffo&b=3&s=f5; expires=Sun, 11-May-2025 10:05:44 GMT; path=/; domain=.yahoo.co.jp; Secure"
  [9]=>
  string(21) "Vary: Accept-Encoding"
  [10]=>
  string(31) "X-Content-Type-Options: nosniff"
  [11]=>
  string(27) "X-Frame-Options: SAMEORIGIN"
  [12]=>
  string(55) "X-Vcap-Request-Id: 7dee0351-709b-4dd1-65e6-bc04a594841b"
  [13]=>
  string(31) "X-Xss-Protection: 1; mode=block"
  [14]=>
  string(6) "Age: 0"
  [15]=>
  string(17) "Connection: close"
  [16]=>
  string(99) "Accept-CH: Sec-CH-UA-Full-Version-List, Sec-CH-UA-Model, Sec-CH-UA-Platform-Version, Sec-CH-UA-Arch"
  [17]=>
  string(100) "Permissions-Policy: ch-ua-full-version-list=*, ch-ua-model=*, ch-ua-platform-version=*, ch-ua-arch=*"
  [18]=>
  string(128) "Set-Cookie: XB=1t5ur6ti5pffo&b=3&s=f5; expires=Sun, 11-May-2025 10:05:44 GMT; path=/; domain=.yahoo.co.jp; secure; samesite=none"
}

正常にページが取得できたか判断するのに str_contains を使ってみました。

<?php
$http_response_header = []; //初期化します。
file_get_contents("https://www.yahoo.co.jp");
var_dump( str_contains($http_response_header[0] ?? '','200 OK') );

以上

Scroll to Top