# How To Read a File’s Contents in PHP

PHP provides three built-in functions which allow you to easily read the contents of a file on your webserver. This is useful when, for example, another program may write information to the file and you could access that information through your script.

In this example, we’re going to use the following example 5 line file, saved as file.txt:

In the same directory as file.txt, we’re going to work with the PHP file test.php. We’ll outline the file reading functions below.

readfile() is the least useful of the file functions. As a parameter, it takes a string which specifies the location of the file to read - this can be relative or absolute; since our file is the same directory as the script, we just need to pass the string 'file.txt' as this paramter. We call the function using the code readfile('file.txt') and it prints out the contents of the file straight to the browser:

The disadvantage of readfile() is that it doesn’t allow you to manipulate the file contents before displaying it - the next two functions we’re going to look at will allow you to do that.

## file()

The code file('file.txt') will read the contents of file.txt into an array, which you can then manipulate in your scripts and display yourself. Each line of the file is stored in a seperate element of the array, this means that we can access and manipulate each line of the file seperately using normal array notation.

In this example, we’ve loaded the contents of file.txt into an array called $lines then used foreach to loop through the array and display each line on the user’s browser. We then use $lines[2] to access the third line of the file (the element at array index 2, since line 1 is \$lines[0]).

You may notice that we’ve used a function called htmlspecialchars() when displaying the file’s contents - this enables that special characters used in HTML, such as > and " are displayed correctly. This illustrates the power of file() over readfile() since readfile() was unable to perform this kind of processing.

## get_file_contents()

The last method we will look at is get_file_contents('file.txt') which is similar to file() however rather than returning an array, it returns a string with all the lines of the file. We can manipulate and display this in a similar way as with file():

Since we have no way of seperating the lines with this method, we’ve used the nl2br() function which converts line breaks in the string (represented by the special character \n) into the HTML line break <br /> so that the file will display correctly on the visitor’s browser.

## Example Code

The full contents of test.php is below:

The output from test.php is:

Tags:

Categories:

Updated: