ZetCode

PHP fpassthru 函数

最后修改于 2025 年 4 月 3 日

PHP fpassthru 函数输出文件指针中剩余的所有数据。它对于将大文件直接流式传输到输出非常有效。

基本定义

fpassthru 函数从文件中的当前位置读取数据直到文件末尾 (EOF),并将数据写入输出缓冲区。它返回读取的字节数。

语法:fpassthru(resource $stream): int。该函数对二进制文件很有用,并且需要一个已打开的文件指针。

fpassthru 基本示例

这显示了 fpassthru 输出文件的最简单用法。

basic_fpassthru.php
<?php

declare(strict_types=1);

$file = fopen('example.txt', 'rb');
if ($file) {
    fpassthru($file);
    fclose($file);
}

这将读取并输出 example.txt 的全部内容。文件以二进制模式打开,以便在不同平台之间可靠地读取。

输出图片文件

fpassthru 常用于输出图片等二进制文件。

image_output.php
<?php

declare(strict_types=1);

$imagePath = 'photo.jpg';
$file = fopen($imagePath, 'rb');

if ($file) {
    header('Content-Type: image/jpeg');
    fpassthru($file);
    fclose($file);
    exit;
}

此示例将 JPEG 图片直接流式传输到浏览器。在调用 fpassthru 处理二进制数据之前,必须设置正确的标头。

部分文件输出

您可以将 fseekfpassthru 结合使用以实现部分输出。

partial_output.php
<?php

declare(strict_types=1);

$file = fopen('largefile.bin', 'rb');
if ($file) {
    fseek($file, 1024); // Skip first 1KB
    $bytes = fpassthru($file);
    echo "Output $bytes bytes";
    fclose($file);
}

这将跳过文件的前 1KB,然后再输出其余部分。该函数返回输出的字节数,这对于日志记录可能很有用。

PDF 文件下载

fpassthru 可以通过设置正确的标头来强制下载文件。

pdf_download.php
<?php

declare(strict_types=1);

$pdfFile = 'document.pdf';
$file = fopen($pdfFile, 'rb');

if ($file) {
    header('Content-Type: application/pdf');
    header('Content-Disposition: attachment; filename="downloaded.pdf"');
    fpassthru($file);
    fclose($file);
    exit;
}

这将强制在浏览器中下载 PDF 文件。Content-Disposition 标头会告诉浏览器保存而不是显示文件。

错误处理

与文件操作一起工作时,适当的错误处理非常重要。

error_handling.php
<?php

declare(strict_types=1);

$filePath = 'data.txt';

if (!file_exists($filePath)) {
    die("File not found");
}

$file = fopen($filePath, 'rb');
if (!$file) {
    die("Failed to open file");
}

if (fpassthru($file) === false) {
    die("Error reading file");
}

fclose($file);

此示例包括对文件存在性、打开和读取的基本错误检查。在处理文件时,请始终验证操作。

最佳实践

来源

PHP fpassthru 文档

本教程通过实际示例介绍了 PHP fpassthru 函数,展示了其在高效文件输出方面的用法。

作者

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

列出 所有 PHP 文件系统函数