What Is File_get_contents in PHP

File_get_contents() is one of the popular file handling functions in PHP. There are other similar file handling functions like read() and file(). However file_get_contents() function has its own advantages among all others.

File_get_contents() Function

The primary usage of the file_get_contents() is to read the specified file. It also provides extra features like from where to start and how much to read from the file.

Syntax

file_get_contents($file_path, $file_include_path, $context, $start_position, $max_length)

Explanation

In the file_get_contents() function, we have to pass the file path as a parameter to read the file, and all other parameters are optional.

  1. $file_path – Name of the file which we need to read.
  2. $file_include_path – This is an optional boolean parameter which helps to read a file in the file using the include_path (in Some_other_file.php)
  3. $context – This is a custom parameter to pass a custom parameter.
  4. $start_position – This parameter is used to specify the starting position to read the file.
  5. $max_length – It is used to specify how much to read from the file.

Example 1

<?php 
    // read contents from the text file
    $data = file_get_contents("https://errorsea.com/file.txt");
    echo $data;
?>

Output

Line 1: Cause 'error' is the signal of success Line 2: Errorsea is the Best Programming Website

Note: file_get_contents() function can not read line by line.

Example 2

<?php 
    // read first 46 characters from the text file
    $data = file_get_contents("https://errorsea.com/file.txt", FALSE, NULL, 0, 46);
    echo $data; 
?>

Output

Line 1: Cause 'error' is the signal of success

Read Also: How to Include File in PHP [All Methods]

Conclusion

There are some special occasions when we have to read files without new lines and from specific positions to a fixed length. At that time file_get_contents() function helps to fulfill our requirement.

I hope you understand the complete usage of the file_get_contents() function.

Enjoy Coding 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *