PHP | readfile( ) Function

The readfile() function in PHP is an inbuilt function which is used to read a file and write it to the output buffer. The filename is sent as a parameter to the readfile() function and it returns the number of bytes read on success, or FALSE and an error on failure.
By adding an ‘@’ in front of the function name the error output can be hidden.

Syntax:

readfile(filename, include_path, context)

Parameters Used:
The readfile() function in PHP accepts three parameters.



  1. filename : It is a mandatory parameter which specifies the file name.
  2. include_path : It is an optional parameter which can be set to 1 if you want to search for a file in the include_path in php
  3. context : It is an optional parameter which specifies the behavior of the stream.

Return Value:
It returns the number of bytes read on success, or FALSE and an error on failure.

Note: URL can be used as a filename with this function if the fopen wrappers have been enabled.

Errors And Exception

  • Turning off output buffering before calling Readfile() function may help in reading larger files into the memory.

Examples:

Input : echo readfile("gfg.txt");
Output : A computer portal for geeks!

Input : $myfile = @readfile("gfg.txt");
        if (!$myfile) 
        {
             print "File could not be opened";
        }
Output : A computer portal for geeks!

Below programs illustrate the readfile() function.

Suppose there is a file named “gfg.txt”

Program 1

filter_none

edit
close

play_arrow

link
brightness_4
code

<?php 
  
// writing file contents on the output
//  buffer using readfile() function
echo readfile("gfg.txt");
  
?>

chevron_right


Output:

A computer portal for geeks!

Program 2

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Output:

A computer portal for geeks!

Reference:
http://php.net/manual/en/function.readfile.php



My Personal Notes arrow_drop_up

I am a technology enthusiast who has a keen interest in programming I am pursuing Engineering in Computer Science from GEU, Dehradun I like to unwind by watching movies and English sitcomsI have a keen interest in music

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : joelgray2703