SOFTELメモ Developer's blog

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

【php】file_get_contents(‘http://~’)で404 Not Foundでも内容を取得したい

問題

HTTPステータス 404 Not Found が返ってくるページ(存在しないページ、カスタムの404ページなど)って、file_get_contents()したときの戻り値はfalseですよね。

404ページの内容って取得できないの?

file_get_contents('https://www.softel.co.jp/404ページ'); // → false

答え

エラーを無視して内容を取得させるHTTPコンテキストオプションがある。

ignore_errors を true にする(デフォルトはfalse)。

<?php
//HTTPコンテキストオプションを設定
$context = stream_context_create();
stream_context_set_option($context, 'http', 'ignore_errors', true);

//404ページをfile_get_contentsする
$html = file_get_contents("https://www.softel.co.jp/123", false, $context);

//404ページのHTMLの確認
var_dump(htmlspecialchars($html));

//404ページのレスポンスヘッダの確認
var_dump($http_response_header);

参考

http://www.php.net/manual/ja/context.http.php

http://www.php.net/manual/ja/reserved.variables.httpresponseheader.php

関連するメモ

コメント