ZetCode

PHP fflush 函数

最后修改于 2025 年 4 月 3 日

PHP 的 fflush 函数强制将所有缓冲的输出写入文件指针。 当您需要立即输出而无需等待缓冲区填满时,它很有用。

基本定义

fflush 函数将输出刷新到文件。它接受一个参数:文件指针资源。 成功时返回 true,失败时返回 false。

语法:fflush(resource $stream): bool。 该函数特别适用于像 STDOUT 或文件句柄这样的输出流。

fflush 基本示例

这展示了 fflush 与文件句柄的最简单用法。

basic_fflush.php
<?php

declare(strict_types=1);

$file = fopen('output.txt', 'w');
fwrite($file, "Hello, World!\n");
fflush($file);
fclose($file);

这写入一个文件并立即刷新缓冲区。 如果没有 fflush,数据可能会保留在缓冲区中,直到脚本结束或缓冲区填满。

刷新 STDOUT

fflush 可以与 STDOUT 一起使用,用于实时命令行输出。

stdout_flush.php
<?php

declare(strict_types=1);

for ($i = 0; $i < 5; $i++) {
    echo "Progress: $i\n";
    fflush(STDOUT);
    sleep(1);
}

这演示了在 CLI 脚本中的实时输出。 如果没有 fflush,输出可能会被缓冲并在脚本完成时一次性出现。

刷新网络流

fflush 在写入网络套接字或管道时很有用。

socket_flush.php
<?php

declare(strict_types=1);

$socket = fsockopen('example.com', 80);
fwrite($socket, "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n");
fflush($socket);

while (!feof($socket)) {
    echo fgets($socket, 128);
}
fclose($socket);

这会将 HTTP 请求立即刷新到服务器。 网络编程通常需要立即传输数据,而不是缓冲输出。

使用 fflush 的错误处理

此示例显示了在使用 fflush 时的正确错误处理。

error_handling.php
<?php

declare(strict_types=1);

$file = fopen('data.log', 'a');
if ($file === false) {
    die("Failed to open file");
}

$bytes = fwrite($file, "Log entry\n");
if ($bytes === false) {
    die("Failed to write to file");
}

if (!fflush($file)) {
    die("Failed to flush output");
}

fclose($file);

正确的错误处理可确保数据完整性。 在进行文件处理过程的下一步之前,会检查每个操作是否成功。

性能注意事项

此示例演示了频繁刷新的性能影响。

performance.php
<?php

declare(strict_types=1);

$file = fopen('large_data.txt', 'w');

// Without flushing
$start = microtime(true);
for ($i = 0; $i < 10000; $i++) {
    fwrite($file, "Line $i\n");
}
$timeNoFlush = microtime(true) - $start;

// With flushing
rewind($file);
$start = microtime(true);
for ($i = 0; $i < 10000; $i++) {
    fwrite($file, "Line $i\n");
    fflush($file);
}
$timeWithFlush = microtime(true) - $start;

fclose($file);

echo "Without flush: $timeNoFlush seconds\n";
echo "With flush: $timeWithFlush seconds\n";

频繁刷新会显著影响性能。 此示例比较了在每次写操作后进行刷新和不进行刷新时的执行时间。

最佳实践

来源

PHP fflush 文档

本教程介绍了 PHP fflush 函数,并提供了实际示例,展示了它在不同场景中的用法。

作者

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

列出 所有 PHP 文件系统函数