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 above PHP example:

php rewind example

Let me create another example on 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 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:

rewind(filePointer)

PHP Online Test


« Previous Tutorial Next Tutorial »

Follow/Like Us on Facebook




Subscribe Us on YouTube