PHP fread() | Read a File

The PHP fread() is used when we need to read the content of an opened file, using its pointer. For example:

<?php
   $fp = fopen("codescracker.txt", "r");
   $content = fread($fp, 4);
   echo $content;
   fclose($fp);
?>

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

php fread function

Since, I've specified 4 as length, to read only first 4 characters of the file. Therefore the output produced by above example is Hey,. That is the first four character of the file codescracker.txt. Here is the snapshot of the file, codescracker.txt:

php read a file fread

PHP fread() Syntax

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

fread(filePointer, length)

Both parameters are required. The filePointer refers to the file pointer, whereas the length parameter is used to specify the length of characters to read from the file.

If you want to read the complete content of a file, then you can use filesize() function to calculate the size of an unknown file, and apply it as the length parameter. For example:

<?php
   $file = "codescracker.txt";
   $fp = fopen($file, "r");
   $content = fread($fp, filesize($file));
   echo $content;
   fclose($fp);
?>

Now the output of above PHP example should be:

php read a file example

Here is the modified version of above example:

<?php
   $file = "codescracker.txt";
   $fp = fopen($file, "r");
   if($fp)
   {
      $content = fread($fp, filesize($file));
      echo $content;
      fclose($fp);
   }
   else
      echo "<p>Unable to open the file</p>";
?>

PHP Read a File Line by Line

To read a file, line by line, use feof() followed by fgets(), in this way:

<?php
   $file = "codescracker.txt";
   $fp = fopen($file, "r");
   if($fp)
   {
      while(!feof($fp))
      {
         $line = fgets($fp);
         echo $line;
         echo "<br>";
      }
   }
   else
      echo "<p>Unable to open the file</p>";
?>

The output of above PHP example should be:

php read a file fread example

PHP Read a File Character by Character

To read a file, character by character, use feof() followed by fgetc(), in this way:

<?php
   $file = "codescracker.txt";
   $fp = fopen($file, "r");
   if($fp)
   {
      while(!feof($fp))
      {
         $character = fgetc($fp);
         if($character == "\n")
            echo "<br>";
         else
            echo $character;
      }
   }
   else
      echo "<p>Unable to open the file</p>";
?>

You will get the exact output as of previous example.

PHP Online Test


« Previous Tutorial Next Tutorial »

Follow/Like Us on Facebook




Subscribe Us on YouTube