298 of 410 menu

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

rewind(resource $handle);

Example

Reset the file pointer after reading the first line:

<?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:

'First line' 'First line'

Example

Try to read the file twice without rewind:

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

Code execution result:

'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
byenru