関数 readfile

関数 readfile はファイルを読み取り、その内容を即座に出力バッファに送信します。 読み取ったバイト数、またはエラーの場合は false を返します。最初のパラメータはファイルへのパス、 2番目(オプション)は include_path でのファイル検索フラグ、3番目(オプション)はストリームコンテキストです。

構文

phpreadfile(
  string $filename,
  bool $use_include_path = false,
  ?resource $context = null
): int|false

例

テキストファイルの内容を出力します:

php<?php
  $res = readfile('example.txt');
  echo "read bytes: " . $res;
?>

例

存在しないファイルを読み取ろうとします:

php<?php
  $res = readfile('nonexistent.txt');
  
  if ($res === false) {
    echo "Failed to read file";
  }
?>

例

include_path フラグの使用:

php<?php
  $res = readfile('config.ini', true);
  echo $res !== false ? "Read success" : "Read failed";
?>

関連項目

  • ファイルを文字列に読み込む関数 file_get_contents、
  • ファイルの残りを出力する関数 fpassthru、
  • ファイルを配列に読み込む関数 file、