ZetCode

PHP readfile 函数

最后修改于 2025 年 4 月 3 日

PHP readfile 函数读取一个文件并将其写入输出缓冲区。它对于文件下载和直接提供静态文件非常有效。

基本定义

readfile 函数读取一个文件并将其写入输出缓冲区。它返回读取的字节数,或在失败时返回 false。

语法: readfile(string $filename, bool $use_include_path = false, resource $context = ?): int|false。该函数是二进制安全的。

基本的 readfile 示例

这展示了 readfile 输出文件内容的最简单用法。

basic_readfile.php
<?php

declare(strict_types=1);

$file = "example.txt";
$bytes = readfile($file);

echo "\nRead $bytes bytes";

这会读取 "example.txt" 并输出其内容。该函数返回读取的字节数,我们将其显示在文件内容之后。

文件下载示例

readfile 通常用于带有正确标头的下载文件。

file_download.php
<?php

declare(strict_types=1);

$file = "document.pdf";
header("Content-Type: application/pdf");
header("Content-Disposition: attachment; filename=\"" . basename($file) . "\"");

readfile($file);
exit;

这会将 PDF 文件作为下载发送,并附带适当的标头。浏览器将提示用户保存文件而不是显示它。

检查文件是否存在

在尝试读取文件之前检查文件是否存在是一个好习惯。

file_exists.php
<?php

declare(strict_types=1);

$file = "data.txt";

if (file_exists($file)) {
    readfile($file);
} else {
    echo "File not found";
}

这会先检查文件是否存在,如果文件丢失则可以防止警告。file_exists 函数用于此检查。

使用 include_path

第二个参数允许在 include path 中搜索文件。

include_path.php
<?php

declare(strict_types=1);

$file = "config.ini";
$bytes = readfile($file, true);

if ($bytes === false) {
    echo "Failed to read file";
}

当为 true 时,第二个参数会使 PHP 在 include path 中搜索文件。这对于可能位于不同位置的文件很有用。

Stream Context 示例

第三个参数允许使用自定义流上下文进行特殊操作。

stream_context.php
<?php

declare(strict_types=1);

$context = stream_context_create([
    "http" => [
        "method" => "GET",
        "header" => "Accept-language: en\r\n"
    ]
]);

$file = "http://example.com/data.txt";
$bytes = readfile($file, false, $context);

if ($bytes !== false) {
    echo "\nSuccessfully read $bytes bytes";
}

这演示了使用自定义 HTTP 标头读取远程文件。流上下文会修改文件的访问方式,添加语言偏好。

最佳实践

来源

PHP readfile 文档

本教程通过实用的示例展示了 PHP readfile 函数在不同场景下的用法。

作者

我叫 Jan Bodnar,是一位充满热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直撰写编程文章。迄今为止,我已撰写了 1,400 多篇文章和 8 本电子书。我在编程教学方面拥有十多年的经验。

列出 所有 PHP 文件系统函数