PHP Tutorial - PHP file_get_contents() Function


file_get_contents() takes the filename to open. It returns the contents of the file as a string, complete with new line characters \n where appropriate.

The file_get_contents() reads a file into a string.


PHP file_get_contents() Function has the following syntax.



ParameterIs RequiredDescription
pathRequired.File to read
include_pathOptional.Set to '1' to search for the file in the include_path defined in php.ini
contextOptional.Context of the file handle. Context is a set of options that can modify the behavior of a stream. Can be skipped by using NULL.
startOptional.Where in the file to start reading.
max_lengthOptional.How many bytes to read.


The function returns the read data or FALSE on failure.


This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.

Use the === operator for testing the return value of this function.


<?PHP//from w  ww  .jav  a2s . co  m
      $filename = "test.txt";
      $filestring = file_get_contents($filename);
      if ($filestring) {
             print $filestring;
      } else {
             print "Could not open $filename.\n";
      echo file_get_contents("test.txt");

The code above generates the following result.

Example 2

The following code shows how to get and output the source of the homepage of a website.

$homepage = file_get_contents('');
echo $homepage;

The code above generates the following result.

Example 3

The following code shows how to read entire file into a string.

//from  ww  w  . ja v  a 2  s  .com
// Create a stream
$opts = array(
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n"

$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
$file = file_get_contents('', false, $context);