The rewind Function

The rewind function resets the file pointer to the beginning. This is useful when you need to reread a file or return to its beginning after some operations. The function takes one parameter - a file pointer, returned by the fopen function.

Syntax

phprewind(resource $handle);

Example

Reset the file pointer after reading the first line:

php<?php
  $file = fopen('test.txt', 'r');
  echo fgets($file); // Read first line
  rewind($file);     // Reset pointer
  echo fgets($file); // Read first line again
  fclose($file);
?>

Code execution result:

php'First line'
'First line'

Example

Try to read the file twice without rewind:

php<?php
  $file = fopen('test.txt', 'r');
  echo fread($file, filesize('test.txt'));
  echo fread($file, filesize('test.txt'));
  fclose($file);
?>

Code execution result:

php'File content'
''

See Also

  • the fseek function,
    which moves the file pointer
  • the ftell function,
    which returns the current position
  • the feof function,
    which checks for end-of-file