• PHP File provides various functions to read data.
  • There are different functions that allow you to read all file data, read data character by character and read data line by line.
  • The PHP file available read functions are given below, they are:
    1. fread ()
    2. fgets ()
    3. fgetc ()

PHP Read File- fread ()

  • PHP fread () function is used to read data of the file and it consists of two arguments, they are file size and file resource.

Sample Code

<?php    
$filename = "c:\\file1.txt";
$fp = fopen($filename, "r");//open file in read mode

$contents = fread($fp, filesize($filename));//read file

echo "<pre>$contents</pre>";//printing data of file
fclose($fp);//close file
?>

Output

PHP Read file- fgets ()

  • To read single line from the file PHP fgets () function is used.

Sample Code

<?php    
$fp = fopen("c:\\file1.txt", "r");//open file in read mode
echo fgets($fp);
fclose($fp);
?>

Output

PHP Read file- fgetc ()

  • To read single character from the file PHP fgetc () function is used and use! feof () function inside the while loop to get all data using fgetc () function.

Sample Code

<?php    
$fp = fopen("c:\\file1.txt", "r");//open file in read mode
while(!feof($fp)) {
echo fgetc($fp);
}
fclose($fp);
?>

Output

Categorized in: