<< PHP Open File | PHP Tutorials | PHP Write to File >>

PHP Read File

When reading a file there are certain things to keep in mind. The PHP parser will not automatically read the entire content of the file. You must define how much of the data you want out of the file.

There are four different modes that can be used when trying to open a file for reading. They include: r, r+, w+ and a+. If you want to only read from a file the only one you need to remember is the r mode.

Also note that there must be at least 1 byte of information inside the file for PHP to read it. If there is a length of 0, it will return an error and halt the script.

The fread() Function

If you want to test this out, make the example.txt file on your site and put it in the directory you wish to work with this code. It must have some content in it or the code will return an error. Here is the code:

<?php
$file_name = 'example.txt';
$file_handle = fopen($file_name, 'r') or die('Error opening file.');

// Requires the file handle and the amount of bytes
$file_data = fread($file_handle, filesize($file_name));
fclose($file_handle);

// Print the data read
echo $file_data;
?>

In the above example you can see that we used the fopen() function to open the file and put the handle in the $file_handle variable. Next we have a new function, the fread() function.

The fread() function requires two parameters. The first parameter is the handle for the file (in this case $file_handle). The second parameter is the amount of bytes (characters) you wish to retrieve from the file. You can see in the example I used the filesize() function. This retrieves the file size of the file we are opening, so we can retrieve all the data.

Next the code will close the handle for the file and then output the file data.

Read a Little

As I said above, you don't have to read the entire file. For example, if you had a file that looked like this (example.txt):

The quick brown fox jumps over the lazy dog.

And you only wanted to read 15 bytes from it, you could do it like this:

<?php
$file_handle = fopen('example.txt', 'r') or die('Error opening file.');

// Requires the file handle and then amount of bytes
$file_data = fread($file_handle, 15);
fclose($file_handle);

// Print the data read
echo $file_data;
?>

This will successfully read 15 bytes from the file and output this:

The quick brown

You can change that number to anything you want, as long as it doesn't go over the entire length of the file.

<< PHP Open File | PHP Tutorials | PHP Write to File >>