Skip to content
Related Articles

Related Articles

PHP | file_get_contents() Function
  • Last Updated : 03 May, 2018
GeeksforGeeks - Summer Carnival Banner

The file_get_contents() function in PHP is an inbuilt function which is used to read a file into a string. The function uses memory mapping techniques which are supported by the server and thus enhances the performances making it a preferred way of reading contents of a file.

The path of the file to be read is sent as a parameter to the function and it returns the data read on success and FALSE on failure.

Syntax:

file_get_contents($path, $include_path, $context, 
                              $start, $max_length)

Parameters: The file_get_contents() function in PHP accepts one mandatory parameter and four optional parameters.

  1. $path: It specifies the path of the file or directory you want to check.
  2. $include_path: It is an optional parameter which searches for a file in the file in the include_path (in php.ini) also if it is set to 1.
  3. $context: It is an optional parameter which is used to specify a custom context.
  4. $start: It is an optional parameter which is used to specify the starting point in the file for reading.
  5. $max_length: It is an optional parameter which is used to specify the number of bytes to be read.

Return Value: It returns the read data on success and FALSE on failure.



Errors And Exception:

  1. If you want to open a file with special characters, such as spaces, it needs to be encoded first using urlencode().
  2. The file_get_contents() function returns Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE.
  3. An E_WARNING level error is generated if filename cannot be found, maxlength is less than zero, or if seeking to the specified offset in the stream fails.

Examples:

Input:  file_get_contents('https://www.geeksforgeeks.org/');
Output: A computer science portal for geeks

Input:  file_get_contents('gfg.txt', FALSE, NULL, 0, 14);
Output: A computer science portal for geeks

Below programs illustrate the file_get_contents() function.

Program 1:




<?php
  
// reading contents from the
// geeksforgeeks homepage
$homepage = file_get_contents("https://www.geeks
                                 forgeeks.org/");
echo $homepage;
  
?>

Output:

A computer science portal for geeks

Program 2:




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

Output:

A computer science portal for geeks

Reference:
http://php.net/manual/en/function.file-get-contents.php

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :