PHP Function Reference

PHP rewind() Function



The PHP rewind() function sets the file position indicator for specified file stream to the beginning of the file stream.

Syntax

rewind(stream)

Parameters

stream Required. Specify the file pointer. It must be valid, and must point to a file successfully typically opened by using fopen() function.

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.

The example below describes the use this function while reading a file.

<?php
//open the file in read mode
$fp = fopen("test.txt", "r") or 
         die("Unable to open file!");

//reading the first line from the file
echo fgets($fp, 4096);

//setting the file pointer to the start
rewind($fp);

//reading the first line again
echo fgets($fp, 4096);

//close the file
fclose($fp);
?>

The output of the above code will be:

This is a test file.
This is a test file.

Example:

Consider one more example where rewind() function is used to set the file position to start after appending some data to the file and then read the updated content from the beginning of the file.

<?php
//open the file in append mode
$fp = fopen("test.txt", "a+");

//append some data to it
fwrite($fp, PHP_EOL.'Third line is added.');

//setting the file pointer to the start
rewind($fp);

//reading the file line by line
//and displaying the read content
while(!feof($fp)) {
  echo fgets($fp);
}

//close the file
fclose($fp);
?>

The output of the above code will be:

This is a test file.
It contains dummy content.
Third line is added.

❮ PHP Filesystem Reference