PHP File Open/Read

File handling is an important part of any web application. You often need to open and process a file for different tasks. PHP has many functions for file creation, reading, writing, delete and etc.

In File handling before read/write we need to open a file and close the file after performing operations.

Sample Text File

Assume you have the following sample text file at your server directory. and it’s name is file.txt

PHP = PHP Hypertext Preprocessor
HTML = Hyper Text Markup Language
CSS = Cascading Style Sheets
JS = Java Script
SQL = Structured Query Language
XML = EXtensible Markup Language
AJAX = Asynchronous JavaScript and XML

Reading Complete File

PHP have different function for reading but right now we will study a simple function which will take the file name and return the full content of a file.

	//Read a entire file with Single Function
	//Return the Total Number of Bytes in return which is read by this function
	echo readfile("file.txt");

Read file single line Example

Below example will demonstrate the fget function which will read the file line by line.

	//Read a single line from file with fgets
	$fh=fopen("file.txt",'r') or die("file not found"); 
	$text=fgets($fh); //Read Single Line
	echo $text;

Read the file with FEOF & FGET Method

This example will demonstrate how to read the file line by line till the file pointer reach at the end of file.

	//Read a entire file with fget and feof functions
	$fh=fopen("file.txt","r") or die("file not found");
	//output one line until end of file
		echo fgets($fh)."
"; } ?>

Read the file with fread

fread function provides the functionality to the read the file till the specific byte.

	//Read a file using fread function
	$fh=fopen("file.txt",'r') or die("file not found");
	echo $text;

Read Entire File with file_get_content

file_get_content provides the ability to read the remote files and return a string.

	//Read a file using file_get_content
	echo $file;