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.


	<?php
	//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.


	<?php
	//Read a single line from file with fgets
	$fh=fopen("file.txt",'r') or die("file not found"); 
	$text=fgets($fh); //Read Single Line
	fclose($fh);
	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.


	<?php
	//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
	while(!feof($fh)){
		echo fgets($fh)."
"; } ?>

Read the file with fread

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


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

Read Entire File with file_get_content

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


	<?php
	//Read a file using file_get_content
	$file=file_get_content("https://www.google.com");
	echo $file;
	?>