So now we know how to create, open and write to files in PHP. In this PHP tutorial, we will go a step further which is to actually read some data from a file. Ultimately, we will want to get back some of the data that we stored in our files earlier. This is where reading from a file comes in.
PHP provides a handy function which performs the heavy lifting for us. To read from a file in PHP, we use the appropriately named fread function. This function is a simple one and takes only 2 parameters. Have a look at the tutorial below.
The syntax for the fread command is simple enough.
As usual, $fileHandle is a variable to tell PHP the particular file we will be reading from. The $length variable is a variable that tells PHP how much bytes to read from the file.
We are assuming that the file "test.txt" is the same as the one written in the PHP Write to File example. The contents are:
The code below shows how to read from that file in PHP:
<?php $file = "test.txt"; $fileHandle = fopen($file, 'r') or die("Error opening file"); $data = fread($fileHandle, 14); // 14 means read only 14 bytes echo $data; fclose($fileHandle); // close the file since we're done ?>
The result would be:
Note that reading from the file will stop when the end of the file is reached or when the amount of bytes specified when reading is reached, whichever comes first.
We might not immediately know the size of a file so if we wanted to read all of it we could do something like this:
<?php $file = "test.txt"; $fileHandle = fopen($file, 'r') or die("Error opening file"); $data = fread($fileHandle, filesize($file)); echo $data; fclose($fileHandle); // close the file since we're done ?>
Note that the filesize command takes the filename as an argument and not the file handle.
The above code would yield:
That is all there is to reading a file in PHP. Remember that once finished with a file, it is a good idea to close the file to prevent any resource conflicts.
We hope you found this PHP read file tutorial useful.