How to Read Contents of a File Using PHP

PHP



In this article, we show how to read contents of an existing file that you have in a directory on a server.

Say, you have an existing file already in a directory on your server and you want to read the contents of that file.

Well, with PHP, you can read the contents of a file without having to go that file and open it up and read it.

Since PHP is a server side language, it can access any file in a directory on your server and read the contents of it without you having to directly go to that file.

Before I go over to the PHP code, look at the file below.

This is the contents of the file, samplepage.txt.

This website gives tutorials on electronics and programming. This website is written in HTML, PHP, and Javascript


So you can see the contents of the file above. The statement "This website gives tutorials on electronics and programming. This website is written in HTML, PHP, and Javascript" is output.

So you've read the contents of a file using PHP without having to manually go to the file and write it.

So how is this done in PHP code?

This is shown below.


PHP Code

The code to read the contents of a file using PHP is shown below.



So the code is extremely simply.

All you have to do to read the contents of a file is to use the PHP file_get_contents() function. The only parameter that this function needs is the pathway and the filename.

Since we are writing the contents of our file to the current directory (right now this article is published in the Articles directory of this website), this file named samplepage.txt is saved in the samplepage.txt file in the Articles directory. However, if we were writing to the subdirectory named 'files', for instance, inside the Articles directory, the first parameter would be 'files/samplepage.txt'.

Then to be able to read the contents of the file, you have to output it. We do this through the well-known PHP echo() function.

So this just shows you briefly how to read the contents of a file using the PHP file_get_contents() function.


Related Resources

How to Write Contents to a File Using PHP

How to Copy a File Using PHP

How to Rename a File Using PHP

How to Delete a File Using PHP

How to List All Files in a Directory using PHP





HTML Comment Box is loading comments...