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/blog/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"
}