PHP Read File

The available PHP file read functions are given below.

  • fread() - It is used to read the content of the file
  • fgets() - It is used to read single line from the file.
  • fgetc() - It is used to read single character from the file

1. fread() function is used to read the content of the file

string fread (resource $handle, int $length); 
<?php 
  $file_name = "c:\folder\resource.txt";
  $handle = fopen($file_name, "r");
  $file_contents = fread($handle, filesize($file_name));
  echo $file_contents;
  fclose($handle);
?>

Output:

This is the first line
This is the second line
This is the third line

2. fgets() function is used to read single line from the file.

string fread (resource $handle, int $length); 
<?php 
  $file_name = "c:\folder\resource.txt";
  $handle = fopen($file_name, "r");
  echo fgets($handle);
  fclose($handle);
?>

Output:

This is the first line

3. fgetc() function is used to read single character from the file.

string fread (resource $handle); 
<?php 
  $file_name = "c:\folder\resource.txt";
  $handle = fopen($file_name, "r");
  while ( ! feof($handle)) { 
      echo fgetc($handle);
  } 
  fclose($handle);
?>

Output:

This is the first line This is the second line This is the third line