写给愿意动手的 PHP 开发者
PHP学习网 PHP学习网
公告PHP学习网为公益性网站,致力于为广大PHP爱好者服务
首页/ PHP 函数大全/ 文件与目录/ file_get_contents()
文件与目录 PHP PHP 4.3 file_get_contents

file_get_contents()

把整个文件读成一个字符串,也支持直接读 URL。

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

参数

参数类型说明
$filenamestring文件路径或 URL
$use_include_pathbool是否在 include_path 中查找
$contextresource流上下文,用于设置请求头、超时
$offsetint从第几个字节开始读
$length?int读多少字节

返回值

string|false — 文件内容,失败返回 false。

示例

PHP
$txt = file_get_contents(__DIR__ . '/data.txt');
echo strlen($txt) . ' 字节';

注意

  • 读大文件会把整个内容放进内存,几百 MB 会打满 memory_limit,改用 fopen + fgets。
  • 失败时返回 false 并抛 Warning,用 @ 抑制后要自己判断返回值。
  • 读远程 URL 需要 allow_url_fopen=On,生产环境建议改用 curl 并设超时。

相关函数