When working with PHP applications, we frequently must open a neighborhood file and browse data from it or write data to it. In this text, 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’d like to quickly manipulate files using PHP.
We’ll firstly take a look at what these functions do, after which take a look at examples of how they work.
file() and file_get_contents()
file() and file_get_contents() work in much the identical way. They each read a complete file. Nonetheless, file() reads the file into an array, while file_get_contents() reads the file right into a string. Each of those functions are binary protected, which suggests they could be used for any form of content.
Be extra careful when using file(), since the array returned by it can be separated by a latest line, but each element will still have the terminating newline attached to it.
The fopen() function works in a wholly different way. It should open a file descriptor, which functions as a stream to read or write the file.
The PHP Manual explains it this manner:
In its simplest form, a stream is a resource object which exhibits streamable behavior. That’s, it will probably be read from or written to in a linear fashion, and should have the option to fseek() to an arbitrary location throughout 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() could be used to govern the file. And once we’re done, we will close the stream using fclose().
Take a take a look at the next example:
$filepath = “/usr/local/sitepoint.txt”;
$handle = fopen($filename, “r”);
$contents = fread($handle, filesize($filename));
The functions above provides you with much finer control over files, but they’re much lower level than the file() or file_get_contents() functions, that are preferable to make use of, as stated within the PHP documentation:
file_get_contents() is the popular strategy to read the contents of a file right into a string. It should use memory swapping techniques if supported by your OS to boost performance.
file_get_contents() is fairly straightforward to make use of:
$file_contents = file_get_contents(‘./file.txt’);
It will read the contents of file.txt into $file_contents.
If, as a substitute, we wish just a selected a part of the file, we will do that:
$file_contents = file_get_contents(‘./file.txt’, FALSE, NULL, 20, 14);
It will read 14 characters, ranging from character 20 of file.txt. More information on all of the parameters for file_get_contents() could be found on the official documentation.