PHP rewind() | Move File Pointer to Beginning of File

The PHP rewind() function is used when we need to rewind the file pointer to the beginning of the file. For example:

   $fp = fopen("myfile.txt", "w");
   fwrite($fp, "PHP is Fun!");
   echo "<p>The file pointer position: " .ftell($fp). "</p>";
   echo "<p>Now the file pointer position: " .ftell($fp). "</p>";

The snapshot given below shows the output produced by above PHP example:

php rewind example

Let me create another example on rewind() function in PHP:

   $file = "myfile.txt";
   $fp = fopen($file, "w+");
      fwrite($fp, "PHP is Fun!");
      $content = fread($fp, filesize($file));
      echo $content;
      echo "<p>Unable to open the file</p>";

The output of above PHP example on rewind() function is shown in the snapshot given below:

php rewind function

That is, after writing the text PHP is Fun! to the file named myfile.txt, using the function fwrite(). The file pointer ($fp) goes to the end of the file. Therefore, with the help of rewind() function, the file pointer gets moved to the beginning of the file, and using the fread() function, the content gets read and initialized to $content variable. Finally the value of $content variable gets printed on the output, using the echo statement/keyword.

PHP rewind() Syntax

The syntax of rewind() function in PHP, is:


PHP Online Test

« Previous Tutorial Next Tutorial »

Follow/Like Us on Facebook

Subscribe Us on YouTube