PHP Echo Tutorials

Reading A File Using PHP

Written by phpecho.com   

In this short tutorial, we study how to read a file using PHP and print its contents.

The steps we will follow are -

1. Identify a file
2. Read the file contents
3. Print the contents of the file
4. Close the file

Consider the program below. This does all four steps detailed above. We will explain each line later.

<?php
   $file = ("test.txt");
   $fd = fopen($file, "r+");
   $fstring = fread($fd, filesize($file));
   echo ("File contents given below:<br>");
   echo ($fstring);
   fclose($fd);
   ?>

The first line identifies the file on which we want to do operations and assigns the file location to a variable $file. Note that the file location could be absolute or relative. In case of programs running on a Linux web server, it is better to use relative file paths. In our case, the file test.txt is located in the same folder/directory where the program is executed from.

$fd is the file handle we create to access the file. The file handle is created by the use of the fopen() function. This function takes two parameters - the file path and the mode of operation. In our case we use r+ representing read only as the mode of operation.

The next line assigns the contents of the file to a variable $fstring. For this fread is used. This also takes two parameters - the file handle and the length of the contents of the file. In this case, since we do not know the length of the contents of the file, we use the filesize() function to determine the same. Note that it is dangerous to hard code the length as we may end up with incorrect data to process.

The next two lines are used to print the file content.

The final line is used to close the file handler using fclose(). It takes one parameter - the file handler variable itself.

In case, you want to read one line at a time from the file, then you can use the fgets function. Note that this would be useful only if each line is separated in the file with a new line character. An example on how this works is given below:

<?php
   $file = ("test.txt");
   $fd = fopen($file, "r+");
   $fstring = fgets($fd);
   echo ("First line in the file is :<br>");
   echo ($fstring);
   fclose($fd);
   ?>

Note that fgets takes only one parameter as input when compared to two for fread.

Depending on the file contents, you may decide to use either fgets or fread. If you decide to use fgets, you will probably use it along with a loop control to ensure that all lines are read.