php

PHP file_get_contents() Function

PHP contains many built-in functions to read the content of any existing non-empty file. The file_get_contents() is one of the built-in functions of PHP to read the entire content of an existing file as a string. The syntax of this function is given below.

Syntax:

This function can take five arguments. It returns the entire or particular content of a file if the file exists otherwise returns False.

String|false file_get_contents ( string $filename [, bool $use_include_path = FALSE [, resource $context [, int $offset = 0 [, int $maxlen ]]]] )
  • The first argument is mandatory and it takes the filename that will be read by this function.
  • The second argument is optional and the default value of this argument is False. It the value of this argument is set to True then the file will be searched in the path that is used in the include_path value of the php.ini file.
  • The third argument is optional that is used to specify the valid context resource or null.
  • The fourth argument is optional that is used to set the starting position for reading the file content.
  • The fifth argument is optional that is used to set the maximum length of data that will be read from the file.

Different Uses of file_get_contents() Function

Create or select an existing file for reading by using file_get_contents() function. Here, a text file named os.txt has been created with the following content to use in the examples of this tutorial.

os.txt

Windows 11

Windows 10

Windows 8

Windows 7

Ubuntu 20.10

Ubuntu 20.04

Ubuntu 19

Ubuntu 18

Ubuntu 17

macOS Monterey 12.0.1

OS X El Capitan 10.11.6

Mac OS X Puma 10.1.5

Example-1: Read the Entire File

Create a PHP file with the following script to read the content of an existing file. The file_exists() function has been used to check the file exists or not before reading. The is_readable() function has been used to check the read permission of the file. If the file exists and the file has the read permission then the content of the file will be printed by using the file_get_contents() function.

<?php


//Set an filename

$filename = 'os.txt';


//Check the file exists or not

if (!file_exists($filename)) {

    echo 'File does not exist.';

}

//Check the file has the read permission or not

else if (!is_readable($filename)) {

    echo 'File has no read permission.';

}

//Print the entire content of the file

else

    echo file_get_contents($filename);

?>

Output:

The following output will appear executing the above script. Here, the newline has been omitted.

Example-2: Read the File Partially

Create a PHP file with the following script to read some particular portion of a file instead of reading the full content by using the file_get_contents() function. Here, the filename will be taken from the URL query parameter. Next, the existence and read permission of the file will be checked. The particular portion of the file will read based on the positive starting position and the length and the negative starting position and the length.

<?php


//Check the filename is provided in the URL Query parameter or not

if(isset($_GET['fn']))

{

    //Set an filename

    $filename = $_GET['fn'];


    //Check the file exists or not

    if (!file_exists($filename)) {

        echo 'File does not exist.';

    }

    //Check the file has the read permission or not

    else if (!is_readable($filename)) {

        echo 'File has no read permission.';

    }

    else

    {

        //Print the particular portion of the file based on positive starting position

        echo "<b>Output for the positive starting position:</b><br/>".file_get_contents($filename, null, null, 5, 30);

        //Print the particular portion of the file based on negative starting position

        echo "<br/><b>Output for the negative starting position:</b><br/>".file_get_contents($filename, null, null, -24,
 20);

    }

}

else

    //Print message if the filename is not found

    echo "Filename has not given."

?>

Output:

The following output will appear executing the above script without giving the filename in the URL.

The following output will appear executing the above script if the filename, os.txt is given in the URL parameter that has been created before.

The following output will appear executing the above script if any non-existence file is given in the URL parameter.

Example-3: Read the File Using the include_path Parameter

The value of the include_path parameter has to be set in the php.ini file. The path of this file on Ubuntu is ‘/etc/php/8.0/apache2/php.ini’. Open the file and set the path of the file from where the file will be read. The second argument of the file_get_contents() is required to set true or FILE_USE_INCLUDE_PATH to read the file from the path defined in the include_path parameter.

<?php


//Set an filename

$filename = 'customers.txt';

//Set the second argument value to true

echo "<b>Output-1:</b><br/>".file_get_contents($filename, true);

//Set the second argument value to FILE_USE_INCLUDE_PATH

echo "<br/><b>Output-2:</b><br/>".file_get_contents($filename, FILE_USE_INCLUDE_PATH);


?>

Output:

The following output will appear executing the above script.

Example-5: Read the Content of a URL Using Curl

You have to install the PHP curl library to read the content of an URL address. Run the following command to install the PHP curl module.

$ sudo apt install libapache2-mod-php php-curl

Open the php.ini file and remove the semicolon (;) from the curl extension to enable it.

Create a PHP file with the following script to read the content of an URL address that will be provided in the URL query parameter named url. If the URL address exists, then the content of the URL address will be printed.

<?php


//Check the URL address is provided in the URL Query parameter or not

if(isset($_GET['url']))

{


    //Set the URL value

    $url = $_GET['url'];

    //Use the CURL library to check the existence of the URL

    $curl = curl_init($url);

    curl_setopt($curl, CURLOPT_NOBODY, true);

    if (curl_exec($curl) !== false)

        //Read the page of the URL address

        echo file_get_contents($url);

        else

            echo "URL does not exist.";


}

else

    echo "URL value has not given.";


?>

Output:

The following output will appear executing the above script if no URL address is provided.

The following output will appear executing the above script if the valid URL address, ‘https://linuxhint.com/bash_comments/’ is given.

Example-6: Read the Content of the URL Using Stream Context

Create a PHP file with the following script to read the content of a valid URL address using stream_context_create() and file_get_contents() functions. Here, the second and third arguments of the file_get_contents() has used to read the content of ‘http://www.example.com/’.

<?php


//Create stream for read content of the URL

$options = array(

  'http'=>array(

    'method'=>"GET",

    'header'=>"Accept-language: en\r\n"

  )

);


//Set the context value

$context = stream_context_create($options);


//Read the content of the URL using the HTTP headers

echo file_get_contents('http://www.example.com/', false, $context);


?>

Output:

The following output will appear executing the above script.

Conclusion

The different ways to read the content of a file from different locations and URL addresses by using file_get_contents() have shown in this tutorial. I hope the PHP user will be able to use this function properly after reading this tutorial.

About the author

Fahmida Yesmin

I am a trainer of web programming courses. I like to write article or tutorial on various IT topics. I have a YouTube channel where many types of tutorials based on Ubuntu, Windows, Word, Excel, WordPress, Magento, Laravel etc. are published: Tutorials4u Help.