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:

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

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

php rewind example

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

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

The output of the above PHP example using the 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 the 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 the $content variable. Finally, the value of the $content variable gets printed on the output, using the echo statement/keyword.

PHP rewind() Syntax

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

rewind(filePointer)

Advantages of the rewind() function in PHP

Disadvantages of the rewind() function in PHP

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!