Saturday, November 16, 2024
Google search engine
HomeLanguagesPHP | readfile( ) Function

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 neveropen!

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

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 neveropen!

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 neveropen!

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

Previous article
Next article
RELATED ARTICLES

Most Popular

Recent Comments