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.

Similar Posts