CodesJava

Easy learning with example program codes

PHP Read File


Reading data from a file is a common feature of file handling. In PHP, there are various functions that facilitates different ways and features of reading data from a file, including: reading all file data at a single go, reading the file data line by line and even to read the file data character by character.

PHP Read File functions are:

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

 

PHP fread() function:

To read a file in PHP, fread() function is used.

Syntax:

string fread (resource $filename , int $filesize )  

  • Filename: This parameter represents the name of the file to read.
  • Filesize: This parameter represents maximum length of byte to read.
  • PHP fgets() function:

To read a single line of a file in PHP, fgets() function is used.

Syntax:

string fgets ( resource $filename [, int $filesize ] )

PHP fgetc() function:
To read a single character from a file in PHP, fgetsc() function is used.

Syntax:

string fgetc ( resource $filename )

Example 1: Program to read a file using fread() function:

<!DOCTYPE html>
<html>
<body>
 
<?php
$samplefile = fopen("phpfile.txt", "r");
echo fread($samplefile, filesize("phpfile.txt"));
fclose($samplefile);
?>
 
</body>
</html>

Output

Hello!I am the first line.
And I am the second line.
Hey, I am the third one.

Example 2: Program to read a file using fgets() function:

<!DOCTYPE html>
<html>
<body>
 
<?php
$samplefile = fopen("phpfile.txt", "r");
echo fgets($samplefile);  
fclose($samplefile);
?>
 
</body>
</html>

Output

Hello!I am the first line.
Posted in PHP   
Sign Up/ Sign In
Ask a Question


Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki