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.
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.
file_get_contents($file_path, $file_include_path, $context, $start_position, $max_length)
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.
- $file_path – Name of the file which we need to read.
- $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)
- $context – This is a custom parameter to pass a custom parameter.
- $start_position – This parameter is used to specify the starting position to read the file.
- $max_length – It is used to specify how much to read from the file.
<?php // read contents from the text file $data = file_get_contents("https://cdn.errorsea.com/file.txt"); echo $data; ?>
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.
<?php // read first 46 characters from the text file $data = file_get_contents("https://cdn.errorsea.com/file.txt", FALSE, NULL, 0, 46); echo $data; ?>
Line 1: Cause 'error' is the signal of success
Read Also: How to Include File in PHP [All Methods]
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 🙂