PHP ftell() | Find Current Position of File Pointer

The PHP ftell() function is used when we need to find the current position of file pointer in the file. For example:

<?php
   $file = "fresherearth.txt";
   $fp = fopen($file, "r");
   
   $character = fgetc($fp);
   echo $character;
   $currentPos = ftell($fp);
   echo "<br>The current position of file pointer: " . $currentPos;
   
   fclose($fp);
?>

The output produced by above PHP example on ftell() function is:

php ftell function

And here is the snapshot of the file fresherearth.txt used in above example:

php ftell function example

Let me modify the above example, to convert to a self-defined example on ftell() function in PHP:

<?php
   $fp = fopen("fresherearth.txt", "r");
   
   if($fp)
   {
      echo "<p>The current position: " .ftell($fp). "</p>";
      
      echo "<p>The first character: " .fgetc($fp). "</p>";
      echo "<p>Now the current position: " .ftell($fp). "</p><hr>";
      
      echo "<p>The next (second) character: " .fgetc($fp). "</p>";
      echo "<p>The current position: " .ftell($fp). "</p><hr>";
      
      echo "<p>The next (third) character: " .fgetc($fp). "</p>";
      echo "<p>The current position: " .ftell($fp). "</p>";
      
      fclose($fp);
   }
   else
      echo "<p>Unable to open the file</p>";
?>

Now the output should be:

php ftell example

PHP ftell() Syntax

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

ftell(filePointer)

PHP Online Test


« Previous Tutorial Next Tutorial »