PHP Function Reference

PHP fflush() Function



The PHP fflush() function writes all buffered output to an open file.

Syntax

fflush(stream)

Parameters

stream Required. Specify the file pointer to write the buffered output to. It must be valid, and must point to a file successfully opened by fopen() or fsockopen() (and not yet closed by fclose()).

Return Value

Returns true on success or false on failure.

Example:

Lets assume that we have a file called test.txt. This file contains following content:

This is a test file.
It contains dummy content.

In the example below, fflush() function is used to writes buffered output to this file.

<?php
$filename = 'test.txt';

$fp = fopen($filename, 'r+');

//set the file position to the start
rewind($fp);

//write 'Hello World!' at start
fwrite($fp, 'Hello World!');
fflush($fp);

//truncate rest of the content
ftruncate($fp, ftell($fp));

//close the file
fclose($fp);

//checking the content of the file
$fp = fopen("test.txt", "r");
while(!feof($fp)) {
  echo fgets($fp);
}
fclose($fp);
?>

The output of the above code will be:

Hello World!

❮ PHP Filesystem Reference