Chapter 9. File Access

Reading and writing files is common in PHP applications. Configuration and template files provide a way to customize a web application, and in order for these files to have their intended effect, a PHP application needs to read and write these files.

Reading and Writing Files

The PHP file_get_contents() API function is one of the easiest and most common ways to read a file. It was added in PHP 4.3.0 and was immediately popular so only very old PHP 4 code does not use it. The following PHP code reads the file named data.txt from the same folder that the PHP file is in. The file is read as a long string that is assigned to the $contents variable:

$contents = file_get_contents('data.txt');
print $contents;

If a file named data.txt does not exist, a false boolean value is assigned to the $contents variable. So, if the data.txt file exists and is readable, a string is returned, but if the data.txt file does not exist or is not readable, a boolean is returned.

As discussed previously, PHP API functions, including file_get_contents(), block until they return. The PHP code after the PHP file_get_contents() API function call does not get executed until the PHP file_get_contents() API function call either completely succeeds or completely fails. There is no callback mechanism for this PHP API.

The previous PHP statement is converted in the following Node.js code. The readFileSync() API function in the fs module is the closest Node.js equivalent to the PHP file_get_contents() ...

Get Node.js for PHP Developers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.