PHP Read File PHP

PHP Read File  

PHP Read File

PHP Read File

PHP provides various functions to read data from file. There are different functions that allow you to read all file data, read data line by line and read data character by character.

The available PHP file read functions are given below.

  • fread()
  • fgets()
  • fgetc()

PHP Read File - fread()

The PHP fread() function is used to read data of the file. It requires two arguments: file resource and file size.

Syntax

  1. string fread (resource $handle , int $length )  

$handle represents file pointer that is created by fopen() function.

$length represents length of byte to be read.

Example

  1. <?php    
  2. $filename = "c:\\file1.txt";    
  3. $fp = fopen($filename, "r");//open file in read mode    
  4.   
  5. $contents = fread($fp, filesize($filename));//read file    
  6.   
  7. echo "<pre>$contents</pre>";//printing data of file  
  8. fclose($fp);//close file    
  9. ?>    

Output

this is first line
this is another line
this is third line
 

PHP Read File - fgets()

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

Syntax

  1. string fgets ( resource $handle [, int $length ] )  

Example

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

Output

this is first line

PHP Read File - fgetc()

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

Syntax

  1. string fgetc ( resource $handle )  

Example

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

Output

this is first line this is another line this is third line

Download free E-book of PHP


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries