LoginSignup
10
12

More than 5 years have passed since last update.

PHP の file_get_contents でステータスコードを取得する

Posted at

PHP の file_get_contents は外部リソースを手軽に扱えるので、Web サービスの API を使うときに便利です。

手軽に使える反面、例外処理をちゃんと考えておかないと 4xx や 5xx のステータスコードが返ってきたときに Warnning エラーが発生します。 file_get_contents でステータスコードを取得するにはひと手間かける必要があります。

$context = stream_context_create(array(
    'http' => array('ignore_errors' => true)
));
$response = file_get_contents('http://example.com/', false, $context);

$pos = strpos($http_response_header[0], '200');
if ($pos === false) {
    // 例外処理
}

ステータスコードによって処理を振り分けるのであれば、正規表現でステータスコードを取り出します。

$context = stream_context_create(array(
    'http' => array('ignore_errors' => true)
));
$response = file_get_contents('http://example.com/', false, $context);

preg_match('/HTTP\/1\.[0|1|x] ([0-9]{3})/', $http_response_header[0], $matches);
$status_code = $matches[1];

switch ($status_code) {
    case '200':
        // 200の場合
        break;
    case '404':
        // 404の場合
        break;
    default:
        break;
}

simplexml_load_file のようにストリームコンテキストを拡張できない関数の場合は、いったん上記の方法で文字列として受け取り simplexml_load_string で処理すればよいでしょう。

10
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
12