PHP 8.3.4 Released!

file_get_contents

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

file_get_contentsファイルの内容を全て文字列に読み込む

説明

file_get_contents(
    string $filename,
    bool $use_include_path = false,
    ?resource $context = null,
    int $offset = 0,
    ?int $length = null
): string|false

この関数は file() と似ていますが、 offset で指定した場所から開始し length バイト分だけ ファイルの内容を文字列に読み込むという点が異なります。 失敗した場合、file_get_contents()false を返します。

file_get_contents()はファイルの内容を文字列に読み込む 方法として好ましいものです。もしOSがサポートしていれば パフォーマンス向上のためにメモリマッピング技術が使用されます。

注意:

空白のような特殊な文字を有する URI をオープンする場合には、 urlencode() でその URI をエンコードする必要があります。

パラメータ

filename

データを読み込みたいファイルの名前。

use_include_path

注意:

定数 FILE_USE_INCLUDE_PATH を使用して インクルードパス から探すことができます。 この定数を使うことは、強い型付け が有効になっている場合は不可能です。なぜなら、 FILE_USE_INCLUDE_PATHint だからです。 true を代わりに使いましょう。

context

stream_context_create() で作成したコンテキストリソース。 独自のコンテキストを使用する必要がない場合は、このパラメータに null を指定します。

offset

元のストリーム上で、読み込みを開始するオフセット位置。 負のオフセットは、ストリームの末尾からのオフセットと解釈されます。

リモートファイルに対するシーク (offset 指定) はサポートしていません。 オフセットが小さい場合はリモートファイルでのシークがうまくいくこともありますが、 これはバッファリングされたストリーム上で動作しているだけのことです。

length

読み込むデータの最大バイト数。 デフォルトは、ファイル終端に達するまで読み込みます。 このパラメータは、フィルタが処理した後のストリームに適用されることに注意しましょう。

戻り値

読み込んだデータを返します。失敗した場合に false を返します。

警告

この関数は論理値 false を返す可能性がありますが、false として評価される値を返す可能性もあります。 詳細については 論理値の セクションを参照してください。この関数の返り値を調べるには ===演算子 を 使用してください。

エラー / 例外

filename が見つからない場合、length がゼロより小さい場合、あるいはストリーム内での指定した offset へのシークが失敗した場合に E_WARNING レベルのエラーが発生します。

file_get_contents() 関数がディレクトリに対して呼び出されると、 Windows では E_WARNING レベルのエラーが発生していました。 PHP 7.4 以降では、Windows 以外のオペレーティングシステムでも同じ動きになっています。

変更履歴

バージョン 説明
8.0.0 length は、nullable になりました。
7.1.0 負の offset をサポートするようになりました。

例1 とあるウェブサイトのホームページのソースの取得と出力

<?php
$homepage
= file_get_contents('http://www.example.com/');
echo
$homepage;
?>

例2 include_path の検索

<?php
// 厳密な型検査が有効な場合。つまり、declare(strict_types=1) の場合
$file = file_get_contents('./people.txt', true);
// 厳密な型検査が有効でない場合
$file = file_get_contents('./people.txt', FILE_USE_INCLUDE_PATH);
?>

例3 ファイルの一部の読み込み

<?php
// 21 文字目から 14 文字ぶん読み込みます
$section = file_get_contents('./people.txt', FALSE, NULL, 20, 14);
var_dump($section);
?>

上の例の出力は、 たとえば以下のようになります。

string(14) "lle Bjori Ro"

例4 ストリームコンテキストの使用

<?php
// ストリームを作成します
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);

$context = stream_context_create($opts);

// 上で設定した HTTP ヘッダを使用してファイルをオープンします
$file = file_get_contents('http://www.example.com/', false, $context);
?>

注意

注意: この関数はバイナリデータに対応しています。

ヒント

fopen wrappers が有効の場合、この関数のファイル名として URL を使用することができます。ファイル名の指定方法に関する詳細は fopen() を参照ください。 サポートするプロトコル/ラッパー には、さまざまなラッパーの機能やその使用法、 提供される定義済み変数などの情報がまとめられています。

警告

IIS のような、いくつかの標準に 対応してない Web サーバーは、PHP に警告を発生させるような手順でデータを送信します。 このようなサーバーを使用する場合は、 error_reporting を警告を発生しないレベルまで小さくする必要があります。 PHP では、https:// ラッパーでストリームをオープンする際に バグがある IIS サーバーソフトウエアを検出することができ、この警告を抑制することができます。 あなたが ssl:// ソケットを作成するために fsockopen() を使用している場合、 自らこの警告を検出し、抑制する必要があります。

参考

add a note

User Contributed Notes 8 notes

up
5
KC
3 months ago
If doing a negative offset to grab the end of a file and the file is shorter than the offset, then file_get_contents( ) will return false.

If you want it to just return what is available when the file is shorter than the negative offset, you could try again.

For example...

$contents = file_get_contents( $log_file, false, null, -4096 ); // Get last 4KB

if ( false === $contents ) {
// Maybe error, or maybe file less than 4KB in size.

$contents = file_get_contents( $log_file, false, null );

if ( false === $contents ) {
// Handle real error.
}
}
up
33
Bart Friederichs
11 years ago
file_get_contents can do a POST, create a context for that first:

<?php

$opts
= array('http' =>
array(
'method' => 'POST',
'header' => "Content-Type: text/xml\r\n".
"Authorization: Basic ".base64_encode("$https_user:$https_password")."\r\n",
'content' => $body,
'timeout' => 60
)
);

$context = stream_context_create($opts);
$url = 'https://'.$https_server;
$result = file_get_contents($url, false, $context, -1, 40000);

?>
up
0
daniel at dangarbri dot tech
1 year ago
Note that if an HTTP request fails but still has a response body, the result is still false, Not the response body which may have more details on why the request failed.
up
-2
soger
1 year ago
There's barely a mention on this page but the $http_response_header will be populated with the HTTP headers if your file was a link. For example if you're expecting an image you can do this:

<?php
$data
= file_get_contents('https://example.net/some-link');

$mimetype = null;
foreach (
$http_response_header as $v) {
if (
preg_match('/^content\-type:\s*(image\/[^;\s\n\r]+)/i', $v, $m)) {
$mimetype = $m[1];
}
}

if (!
$mimetype) {
// not an image
}
up
-1
brentcontact at daha dot us
7 months ago
To prevent mixed content most browsers/functions will use the protocol already used if you specify only // instead of http:// or https://. This is not the case with file_get_contents. You must specify the protocol.

This does not work:
<?php
$jsonData
= file_get_contents('//example.com/file.json');
print
$jsonData;
?>

Specifying only 'example.com/file.json' without the double slash does not work either.

When running on Apache 2.4 , using $_SERVER['REQUEST_SCHEME'] is a better way to be protocol agnostic.
<?php
$jsonData
= file_get_contents($_SERVER['REQUEST_SCHEME'].'://example.com/file.json');
print
$jsonData;
?>

If using another web server, you may have to get the protocol another way or hard code it.
up
-22
Anonymous
2 years ago
if the connection is
content-encoding: gzip
and you need to manually ungzip it, this is apparently the key
$c=gzinflate( substr($c,10,-8) );
(stolen from the net)
up
-24
453034559 at qq dot com
2 years ago
//从指定位置获取指定长度的文件内容
function file_start_length($path,$start=0,$length=null){
if(!file_exists($path)) return false;
$size=filesize($path);
if($start<0) $start+=$size;
if($length===null) $length=$size-$start;
return file_get_contents($path, false, null, $start, $length );
}
up
-29
allenmccabe at gmail dot com
2 years ago
I'm not sure why @jlh was downvoted, but I verified what he reported.

>>> file_get_contents($path false, null, 5, null)
=> ""
>>> file_get_contents($path, false, null, 5, 5)
=> "r/bin"
To Top