PHP ftell(): Find Current Position of File Pointer

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

<?php
   $file = "codescracker.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 the above PHP example on the ftell() function is:

php ftell function

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

php ftell function example

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

<?php
   $fp = fopen("codescracker.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 the ftell() function in PHP is:

ftell(filePointer)

Advantages of the ftell() function in PHP

Disadvantages of the ftell() function in PHP

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!