PHP readfile vs. file_get_contents


The ‘readfile’ function is an inbuilt function in PHP that reads the file directly into the output buffer. The name of the file is passed as a parameter to the function. It returns the number of bytes that were read in case of successfully reading the data. It returns FALSE otherwise −

Example

 Live Demo

<?php
// writing file contents on the output
// buffer using readfile() function
$myfile = @readfile("gfg.txt");
if (!$myfile) {
   print "Sorry, the file could not be opened";
}
?>

Output

This will produce the following output −

Sorry, the file could not be opened

The ‘file_get_contents’ function is an inbuilt function in PHP that loads the file into memory and displays the contents only when the echo function is called. During this phase, the data is copied from memory to the output buffer and then displayed. It uses memory mapping techniques making it an efficient way of reading contents in file.

The path of file that needs to be read is passed as a parameter. The function returns the data that is read from the file as output in case of success and FALSE otherwise −

<?php
// reading 36 bytes startig from
// the 0th character from gfg.txt
$text = file_get_contents(‘text_file_name.txt', FALSE, NULL, 0, 36);
echo $text;
?>

Updated on: 09-Apr-2020

641 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements