Open In App

PHP file_get_contents() Function

In this article, we will see how to read the entire file into a string using the file_get_contents() function, along with understanding their implementation through the example.

The file_get_contents() function in PHP is an inbuilt function that is used to read a file into a string. The function uses memory mapping techniques that are supported by the server and thus enhance the performance making it a preferred way of reading the contents of a file. The path of the file to be read, which 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.  



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

Approach: For getting the file into the string, we will use the file_get_contents() function. For the 1st example, we will specify the URL link as an argument that will redirect to the given site. For the 2nd example, generate the file name “gfg.txt” that contains the data. This function will read the file into a string & render the content accordingly.

Errors And Exceptions:  

Consider the following example.

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

Example 1: The below example illustrate the file_get_contents() function.




<!DOCTYPE html>
  
<body>
    <?php
        // Reading contents from the
        // geeksforgeeks homepage
        $homepage = file_get_contents(
            "https://www.geeksforgeeks.org/");
        echo $homepage;
    ?>
</body>
</html>

Output:

Example 2: This example illustrates getting the file into a string.




<!DOCTYPE html>
<body>
    <?php
        // Reading 36 bytes starting from
        // the 0th character from gfg.txt
        $text = file_get_contents('gfg.txt', false, NULL, 0, 36);
        echo $text;
    ?>
</body>
</html>

Output

A computer science portal for geeks

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


Article Tags :