SOFTELメモ Developer's blog

会社概要 ブログ 調査依頼 採用情報 ...
技術者募集中

file_get_contents(‘http://~’)で404 Not Foundのときの判定

問題

phpで、

file_get_contents('https://www.softel.co.jp/blogs/non-exists-resource');

など実行した結果、ファイルがないときって分かるの?

回答

改めて通信したりしなくても、file_get_contents()のすぐ後にレスポンスヘッダが取得できる。

phpの少々気持ち悪い仕様だが、レスポンスヘッダの各行が配列で、$http_response_headerという変数に格納される。

$ php -r 'file_get_contents("https://www.softel.co.jp/blogs/non-exists-resource"); var_dump($http_response_header);'
PHP Warning:  file_get_contents(https://www.softel.co.jp/blogs/non-exists-resource): failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found
 in Command line code on line 1
array(6) {
  [0]=>
  string(22) "HTTP/1.1 404 Not Found"
  [1]=>
  string(35) "Date: Wed, 16 Nov 2011 03:05:56 GMT"
  [2]=>
  string(14) "Server: Apache"
  [3]=>
  string(19) "Content-Length: 223"
  [4]=>
  string(17) "Connection: close"
  [5]=>
  string(43) "Content-Type: text/html; charset=iso-8859-1"
}

関連するメモ

コメント