PHP file_get_contents(): Read file into a string

The PHP file_get_contents() function is used when we need to read a file into a string. For example:

<?php
   $mystr = file_get_contents("codescracker.txt");
   echo $mystr;
?>

The output of the above PHP example using the file_get_contents() function is:

php file_get_contents function

Following is a snapshot of the opened file codescracker.txt, along with the current directory:

php file_get_contents function example

PHP Read File into String Preserving Newline or LineBreak

As you can see in the snapshot of the file codescracker.txt and the output shown above, the file contains text spread over three lines. But the output produced by the previous example, after getting the content of the file into a string, ignored all newline characters. Therefore, nl2br() comes into play. Here is an example:

<?php
   $mystr = file_get_contents("codescracker.txt");
   $mystr = nl2br($mystr);
   echo $mystr;
?>

Or

<?php
   $mystr = file_get_contents("codescracker.txt");
   echo nl2br($mystr);
?>

Both the examples above will produce the same output, which should be:

php file get contents read file into string

PHP file_get_contents() Syntax

The syntax of the file_get_contents() function in PHP is:

file_get_contents(path, include_path, context, start, length)

The first parameter (path) is required, whereas all three other parameters are optional.

Note: The include_path parameter is used when we need to search the file in the include_path (in php.ini). To do this, we need to specify this parameter as 1.

Note: The context parameter is used to specify the context in which to handle the file.

Note: The start parameter is used when we need to read a file into a string from any particular position. Negative values will be used to read from the specified position, from the end.

Note: The length parameter is used when we need to read a file into a string up to the specified maximum length of characters.

Advantages of the file_get_contents() function in PHP

Disadvantages of the file_get_contents() function in PHP

PHP Online Test


« Previous Tutorial Next Tutorial »


Liked this post? Share it!