- カテゴリ: PHP
- 対応バージョン: Laravel 11・12・PHP 8.2
- 名前空間 / FQCN / コマンド:
file_get_contents - 関連: fopen / fread / readfile / file_put_contents / stream_context_create
- 変更履歴: 目立った仕様変更なし(8.x 系)
要点(TL;DR)
- ファイルやHTTP/HTTPSのURLから内容全体を文字列で取得する関数。
- 最低限の使い方:
$html = file_get_contents('https://example.com'); - よくある罠
allow_url_fopen=Offだと URL 取得に失敗- 大きいファイルでメモリ枯渇(全読み込み)
- HTTPエラー時の扱い(
$http_response_header/ignore_errors)を見落とす
概要
file_get_contents はローカルファイルや各種ストリーム(HTTP/HTTPS 等)から内容を一度に読み込むための最短手。小さな設定ファイルやAPIレスポンスの取得に向きます。大量データや逐次処理が必要な場合はストリーム(fopen/fread)を選びます。
構文 / シグネチャ
string|false file_get_contents(
string $filename,
bool $use_include_path = false,
?resource $context = null,
int $offset = 0,
?int $length = null
)
引数(表)
| 引数 | 型 | 必須 | 既定値 | 説明 |
|---|---|---|---|---|
$filename | string | ✓ | — | パスまたは URL(file://, http://, https:// などのラッパー対応) |
$use_include_path | bool | false | include_path を探索対象に含める | |
$context | resource|null | null | stream_context_create() で作成したコンテキスト(HTTPヘッダ、タイムアウト等) | |
$offset | int | 0 | 読み込み開始位置(0以上) | |
$length | int|null | null | 読み込む最大バイト数(未指定は終端まで) |
- 戻り値:
string(成功) /false(失敗) - 例外/副作用:失敗時に
E_WARNING。ネットワーク I/O。内容全体をメモリに保持。HTTP 取得時は$http_response_headerが設定される。
使用例
最小例
<?php
$file = __DIR__ . '/config.json';
$raw = file_get_contents($file);
if ($raw === false) {
// 失敗時は false。E_WARNING が出るためログも要確認。
throw new RuntimeException("ファイル読込に失敗: {$file}");
}
echo $raw;
実務例:HTTP API をヘッダー/タイムアウト付きで取得
<?php
$url = 'https://api.example.com/v1/items?limit=10';
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => "Accept: application/json\r\nUser-Agent: MyApp/1.0\r\n",
'timeout' => 5, // 秒
'ignore_errors' => true, // 4xx/5xx でも本文を取得
'protocol_version' => 1.1,
],
'ssl' => [
'verify_peer' => true,
'verify_peer_name' => true,
// 必要なら 'cafile' => '/path/to/cacert.pem',
],
]);
$json = file_get_contents($url, false, $context);
if ($json === false) {
throw new RuntimeException("HTTP取得に失敗: {$url}");
}
// ステータス確認(例: "HTTP/1.1 200 OK")
$statusLine = $http_response_header[0] ?? '';
if (!preg_match('#\s(\d{3})\s#', $statusLine, $m) || (int)$m[1] !== 200) {
// エラーレスポンスでも本文が返る場合あり(ignore_errors=true)
// ログ用途に本文も保持
throw new RuntimeException("HTTPエラー: {$statusLine}\nBody: {$json}");
}
$data = json_decode($json, true, 512, JSON_THROW_ON_ERROR);
// ここで $data を利用
よくある落とし穴・注意
- URL取得には設定が必要:
php.iniのallow_url_fopenがOnでないとhttp(s)が使えません。禁止環境では cURL 系を検討。 - メモリ消費:内容を丸ごと返すため大きなファイルは不向き。→
fopen+stream_copy_to_stream/freadで逐次処理。 - HTTPエラー判定:
file_get_contentsは 404/500 でも本文が返る場合(ignore_errors=true)があるため、$http_response_headerのステータス行で確認。 - タイムアウト:既定は
default_socket_timeout。API 取得はhttp.context['timeout']を明示。 - SSL検証:本番は
verify_peer/verify_peer_nameを有効。独自CAはcafileを設定。 - offset/length:全ラッパーで高速なシークができるとは限らず、HTTP等では結局読み捨てで追い越すため効率が悪いことがある。
- 文字コード:戻りはバイト列。表示時の文字化けは
mb_detect_encoding/mb_convert_encoding等で整える。
代替・関連APIとの比較
fopen+fread:逐次読み取りが可能で大容量に強い。制御したいときはこちら。readfile:内容を直接出力。ダウンロード配信などで効率的。file:1行ずつ配列で取得。小さなテキストに便利。file_put_contents:書き込み版の対。- cURL拡張:プロキシ、詳細な TLS、リトライ等が必要なら cURL を選択。
テスト例(Pest)
<?php
// tests/FileGetContentsTest.php
it('reads file content', function () {
$tmp = tempnam(sys_get_temp_dir(), 'fgc_');
file_put_contents($tmp, "hello\nworld");
$got = file_get_contents($tmp);
expect($got)->toBe("hello\nworld");
@unlink($tmp);
});
トラブルシュート(エラー別)
| 症状/エラー | 原因 | 対処 |
|---|---|---|
failed to open stream: No such file or directory | パス誤り/権限不足 | 絶対パスで確認、is_readable()、権限修正 |
failed to open stream: HTTP request failed! | 4xx/5xx、接続失敗 | $http_response_header[0] でステータスを確認、タイムアウト/リトライ |
| URLで常に失敗 | allow_url_fopen=Off | 設定を On、不可なら cURL へ切替 |
| SSL: certificate verify failed | ルート証明書未設定/自己署名 | ssl コンテキストで cafile 指定、正しい証明書を導入 |
| メモリ不足(Fatal error: Allowed memory size…) | 大容量の全読み込み | fopen+逐次処理、分割取得、memory_limit 調整 |
| 文字化け | エンコーディング不一致 | ヘッダー確認、mb_convert_encoding で変換 |
参考リンク
- PHP Manual — file_get_contents: https://www.php.net/manual/function.file-get-contents.php
- PHP Manual — stream_context_create: https://www.php.net/manual/function.stream-context-create.php
- PHP Manual — HTTP コンテキストオプション: https://www.php.net/manual/context.http.php
- PHP Manual — SSL コンテキストオプション: https://www.php.net/manual/context.ssl.php
- PHP Manual — file_put_contents: https://www.php.net/manual/function.file-put-contents.php

