W3docs

fflush()

We understand that you want an article that can outrank the current W3Schools article on the PHP fflush() function. We'll create a comprehensive and detailed

Introduction to PHP fflush() Function

The fflush() function in PHP is used to flush the output buffer of a file pointer. It forces any buffered data to be written to the underlying stream immediately. This is particularly useful for logging, real-time data processing, or ensuring data persistence before a script ends.

The fflush() function accepts one parameter: the file pointer you want to flush. In this article, we'll discuss the syntax and parameters of the fflush() function, along with practical examples of how to use it.

Syntax

The syntax of the fflush() function is as follows:

The PHP syntax of fflush()

bool fflush ( resource $stream )
  • stream: the file pointer to flush

Parameters

The fflush() function takes one required parameter:

  1. $stream: The file pointer you want to flush. This parameter should be a resource created using the fopen() function or a similar stream-creating function.

Return Value

Returns true on success or false on failure. If the stream is not open, is not writable, or the operation fails, the function returns false and may emit a warning.

Examples

Here are some examples of how to use the fflush() function:

Example 1: Flush a file pointer

The following example opens a file, writes data, and immediately flushes the buffer to ensure the data is written to disk:

Flush a file pointer in PHP

<?php

$fileHandle = fopen('example.txt', 'w');
fwrite($fileHandle, 'Hello, World!');
fflush($fileHandle);
fclose($fileHandle);

Example 2: Flush multiple file pointers

The following example demonstrates flushing multiple open file handles:

Flush multiple file pointers in PHP

<?php

$fileHandle1 = fopen('log1.txt', 'a');
$fileHandle2 = fopen('log2.txt', 'a');

fwrite($fileHandle1, 'Data for log 1');
fwrite($fileHandle2, 'Data for log 2');

fflush($fileHandle1);
fflush($fileHandle2);

fclose($fileHandle1);
fclose($fileHandle2);

Note on Output Buffering

Do not confuse fflush() with PHP's output buffering functions like ob_flush(). fflush() operates on file streams (e.g., files, sockets, pipes), while ob_flush() flushes PHP's internal output buffer to the web server or client.

Conclusion

In conclusion, the fflush() function is a useful PHP function that ensures buffered data is immediately written to a file stream. It is essential for applications requiring real-time data persistence, such as logging systems or data processing scripts.

By using the examples provided in this article, you should now be able to use the fflush() function in your PHP code with ease. If you have any questions or concerns about using the fflush() function in PHP, feel free to reach out to us. We'd be happy to help you out.

Practice

Practice

What is the correct usage of the fflush() function in PHP?