Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

PHP | readfile( ) Function

  • Last Updated : 04 Sep, 2019

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




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

Output:

A computer portal for geeks!

Program 2




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

Output:

A computer portal for geeks!

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

My Personal Notes arrow_drop_up
Recommended Articles
Page :