ラボ > PHP:通信絡み

PHPでタイムアウトありのステータスコード関連(file_get_contents())

作成日:2018-02-14, 更新日:2018-02-14

基本

$url = 〇〇〇;
$context = stream_context_create(array(
    'http' => array(
        'timeout' => 〇〇,
    ),
));
$source = file_get_contents($url, false, $context);
if ( $source === false ) {
   if( 0 < count($http_response_header) ) {
      // 取得失敗時のレスポンスコード
      echo $http_response_header[0];
   }
   else {
      // タイムアウト or 存在しないドメイン or 他にも何かあるかも?
   }
}
else {
   // 取得成功:$http_response_header[0]でも確認可能
}

関連項目

PHPでHTTPリクエストのレスポンスヘッダの取得(get_headers()、$http_response_header、cUrl)