Quick Tip: How To Read a Local File with PHP

Share this article

Quick Tip: How To Read a Local File with PHP

When working with PHP applications, we often need to open a local file and read data from it or write data to it. In this article, we’ll briefly review the tools available for doing this.

PHP offers us three native functions for manipulating local files: file(), file_get_contents(), and fopen(). Entire libraries have been written around these functions, but they’re still the go-to options when we need to quickly manipulate files using PHP.

We’ll firstly look at what these functions do, and then look at examples of how they work.

file() and file_get_contents()

file() and file_get_contents() work in much the same way. They both read an entire file. However, file() reads the file into an array, while file_get_contents() reads the file into a string. Both of these functions are binary safe, which means they can be used for any type of content.

Be extra careful when using file(), because the array returned by it will be separated by a new line, but each element will still have the terminating newline attached to it.

fopen()

The fopen() function works in an entirely different way. It will open a file descriptor, which functions as a stream to read or write the file.

The PHP Manual explains it this way:

In its simplest form, a stream is a resource object which exhibits streamable behavior. That is, it can be read from or written to in a linear fashion, and may be able to fseek() to an arbitrary location within the stream.

Simply put, calling fopen() won’t do anything but open a stream.

Once we’ve opened the stream and have a handle on the file, other functions like fread() and fwrite() can be used to manipulate the file. And once we’re done, we can close the stream using fclose().

Examples

Take a look at the following example:

<?php
    $filepath = "/usr/local/sitepoint.txt";
    $handle = fopen($filename, "r");
    $contents = fread($handle, filesize($filename));
    fclose($handle);

The functions above will give you much finer control over files, but they’re much lower level than the file() or file_get_contents() functions, which are preferable to use, as stated in the PHP documentation:

file_get_contents() is the preferred way to read the contents of a file into a string. It will use memory swapping techniques if supported by your OS to enhance performance.

file_get_contents() is fairly straightforward to use:

<?php
    $file_contents = file_get_contents('./file.txt');

This will read the contents of file.txt into $file_contents.

If, instead, we want just a specific part of the file, we can do this:

<?php
    $file_contents = file_get_contents('./file.txt', FALSE, NULL, 20, 14);

This will read 14 characters, starting from character 20 of file.txt. More information on all the parameters for file_get_contents() can be found on the official documentation.

Frequently Asked Questions (FAQs) about Reading Local Files in PHP

What is the difference between file_get_contents() and fopen() in PHP?

Both file_get_contents() and fopen() are used to read files in PHP, but they work in slightly different ways. file_get_contents() reads a file into a string, returning the entire file as a single string. This function is simple and easy to use, but it may not be suitable for large files, as it can consume a lot of memory. On the other hand, fopen() opens a file or URL and returns a resource that can be used with other file-related functions, such as fgets() or fwrite(). This function is more flexible and efficient for large files, as it reads the file line by line.

How can I handle errors when reading files in PHP?

PHP provides several ways to handle errors when reading files. One common method is to use the ‘@’ operator before the function to suppress error messages. Another method is to use the file_exists() function to check if the file exists before trying to read it. You can also use the is_readable() function to check if the file is readable. If an error occurs, these functions will return false, allowing you to handle the error gracefully.

Can I read a file from a remote server in PHP?

Yes, PHP allows you to read files from a remote server using the file_get_contents() or fopen() function with a URL instead of a local file path. However, this feature may be disabled on some servers for security reasons. You can check if it’s enabled by looking at the allow_url_fopen setting in the php.ini file.

How can I read a specific line from a file in PHP?

PHP doesn’t provide a built-in function to read a specific line from a file, but you can achieve this by reading the file into an array using the file() function, then accessing the desired line by its index. Keep in mind that the index starts at 0, so the first line is at index 0, the second line is at index 1, and so on.

How can I read a file in binary mode in PHP?

To read a file in binary mode in PHP, you can use the fopen() function with the ‘b’ flag. This is particularly useful for reading binary files, such as images or executable files. After opening the file, you can read it using the fread() function, which returns the data as a binary string.

How can I read a CSV file in PHP?

PHP provides the fgetcsv() function to read CSV files. This function parses the line it reads for fields in CSV format and returns an array containing the fields read. You can use this function in a loop to read the entire CSV file.

How can I read a file backwards in PHP?

PHP doesn’t provide a built-in function to read a file backwards, but you can achieve this by reading the file into an array using the file() function, then reversing the array using the array_reverse() function.

How can I read a file without locking it in PHP?

By default, PHP doesn’t lock files when reading them. However, if you need to ensure that the file isn’t locked, you can use the flock() function with the LOCK_SH flag before reading the file. This function will attempt to acquire a shared lock, allowing other processes to read the file at the same time.

How can I read a large file efficiently in PHP?

To read a large file efficiently in PHP, you can use the fopen() function to open the file, then use the fgets() function in a loop to read the file line by line. This method is more memory-efficient than reading the entire file into a string or an array, as it only keeps the current line in memory.

How can I read a file and output its contents to the browser in PHP?

To read a file and output its contents to the browser in PHP, you can use the readfile() function. This function reads a file and writes it to the output buffer, which is then sent to the browser. This is a convenient way to serve files to the user, such as images or downloadable files.

Claudio RibeiroClaudio Ribeiro
View Author

Cláudio Ribeiro is a software developer, traveler, and writer from Lisbon. He's the author of the book An IDE Called Vim. When he is not developing some cool feature at Kununu he is probably backpacking somewhere in the world or messing with some obscure framework.

PHP Quick Tips
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week