Handling the File System in PHP

PHP Files

It isn't uncommon that you'll need to write a program that will either read from, or write to, a file on the same machine as your script. Perhaps you're writing to a log file, reading a configuration file, or processing a CSV file? In any case, you're in the right place!

Don't have PHP installed? Check out this side dish first!

Reading and Writing Small or Medium Files Quickly

If you want to get started quickly to read or write a file, there are a couple of functions we'll want to be aware of! The only gotcha' is that these may become less reliable in cases where files are large, as you may run into cases where you run out of system memory available to PHP. For small or "medium" sized files, this will be sufficient, however.

file_get_contents()

This can be used to quickly read a file's contents. Let's suppose in our project we have a file called "hello-world.txt" that contains the text: "Hello, World!". In PHP, we could use the following to store its contents as a string:

<?php $filePath = './hello-world.txt'; $fileContents = file_get_contents($filePath); if($fileContents === FALSE) { echo 'Unable to read the file: ', $filePath; } else { echo 'File successfully read: ', $filePath, "\r\n"; echo $fileContents; // Outputs: 'Hello, World!' } ?>

What if the file was a different format, like JSON? This is a common format on the web, so PHP has us covered here, too! Let's assume we have a file called "about-php.json" with the following contents:

{ "name": "PHP", "full_name": "PHP Hypertext Preprocessor", "date_of_release": "1995-06-08", "author": "Rasmus Lerdorf", "web_site": "https://php.net" }

If we want to use PHP to read, and perhaps output this data, we can still use file_get_contents! To convert this JSON string into a PHP object, however, we'll also want to make use of another function built-in to PHP: json_decode(). Observe:

<?php $filePath = './about-php.json'; $fileContents = file_get_contents($filePath); if($fileContents === FALSE) { echo 'Unable to read the file: ', $filePath; } else { echo 'File successfully read: ', $filePath, "\r\n"; // Attempt to convert JSON string into a PHP object or array: $jsonAsPHPObject = json_decode($fileContents); if($jsonAsPHPObject === NULL) { echo 'JSON contained in file "', $filePath, '" was either invalid, or contained too much nesting.'; } else { echo 'Name: ', $jsonAsPHPObject->name, "\r\n", // Outputs: "Name: PHP" 'Full Name: ', $jsonAsPHPObject->full_name, "\r\n", // Outputs: "Full Name: PHP Hypertext Preprocessor" 'Date of Release: ', $jsonAsPHPObject->date_of_release, "\r\n", // Outputs: "Date of Release: 1995-06-08" 'Author: ', $jsonAsPHPObject->author, "\r\n", // Outputs: "Author: Rasmus Lerdorf" 'Web Site: ', $jsonAsPHPObject->web_site, "\r\n"; // Outputs: "Web Site: https://php.net" } } ?>

Fun fact: file_get_contents can be used to retrieve public web pages too!

file_put_contents()

This is nearly as straightforward as retrieving file contents—the only real difference is we will, naturally, have to let the function know the content we'd like to populate the file with. Remember that file we were reading from before, hello-world.txt? Let's say we want to replace its contents "Hello, World!" with the text "Hello, Digital Diner!":

<?php $filePath = './hello-world.txt'; $newFileContents = 'Hello, Digital Diner!'; $writtenContent = file_put_contents($filePath, $newFileContents); if($writtenContent === FALSE) { echo 'Unable to write to file: ', $filePath; } else { echo 'File successfully written: ', $filePath, "\r\n"; echo $writtenContent; // Outputs: 'Hello, Digital Diner!' } ?>

If you run the above, and then open the hello-world.txt file in your favourite text-editor program, you'll see the updated content! Note that this function replaces the existing content. If you want to add to or edit existing content instead, you'll want to run file_get_contents first and manipulate the string before running file_put_contents.

Reading and Writing Larger Files

Reading Files Line-by-Line

If you want a more structured approach to reading a file line-by-line, in smaller pieces, consider the following functions instead:

Let's create a file with some text, php-frameworks.txt:

Laravel Symphony CodeIgniter Zend Framework CakePHP

Maybe we want to read each line and output it to look a little more like a bulleted list, using PHP—let's give it a shot!

<?php $filePath = './php-frameworks.txt'; $file = fopen($filePath, 'r'); // 'r' = Open in "Read-Only" mode. if($file === FALSE) { echo 'Unable to open file: ', $filePath; } else { echo 'File opened successfully: ', $filePath, "\r\n"; // Let's loop through each line of the file: while(($line = fgets($file)) !== FALSE) { // Keep reading until end-of-file. echo '• ', $line, "\r\n"; // Print the line data (or do what you'd like with it.) } // When you're done, close the file fclose($file); } ?>

Writing Files Line-by-Line

This approach will be similar to our previous example above. We'll need to open the file, and then we are free to write new lines. When we're done, we'll want to close the file. Let's use the same "php-frameworks.txt" file as before, and add a couple of frameworks to it:

<?php // This is the content we want to add to our file: $newFileLines = array( 'Phalcon', 'Yii', 'Slim' ); $filePath = './php-frameworks.txt'; $file = fopen($filePath, 'a'); // 'a' = Open in "Append to End of File" mode (good for adding to a file.) // 'w' = Open in "Write from Beginning of File" mode (good for overwriting a file.) if($file === FALSE) { echo 'Unable to open file: ', $filePath; } else { echo 'File opened successfully: ', $filePath, "\r\n"; // Let's add each of our lines: foreach($newFileLines as $line) { $lineText = "\r\n" . $line; // We need to add the "newline" character ourselves (you can skip this step if you want to write all of your text to one line in the file.) fwrite($file, $lineText); } // When you're done, close the file fclose($file); echo 'File written to successfully: ', $filePath, "\r\n"; } ?>

Have a look at your file in your favourite text-editor program to confirm and admire your additions after running the script!

There are similar functions for dealing with the common file format, CSV, look into: fgetcsv and fputcsv.

Different File Open Modes

Here is a list of the modes available at the time of this article's writing. If you want an up-to-date list, please check the official documentation here instead.

Mode What it Does
r Open a file for reading only, reading will start at the beginning of the file.
r+ Open a file for both reading and writing, starting at the file's beginning.
w Open a file for writing only. The file will be emptied, and writing will start at the beginning of the file.
w+ Open a file for both reading and writing. The file will be emptied, reading and writing will start at the beginning of the file.
a Open a file for writing only, writing will start at the end of the file.
a+ Open a file for both reading and writing, starting at the file's end.
x Create a file for writing only. Will not open an existing file, this mode expects the file to not yet exist (used for creating a new file only.)
x+ Create a file for both reading and writing, starting at the file's beginning. Will not open an existing file, this mode expects the file to not yet exist (used for creating a new file only.)
c Open a file for writing only. Writing will start at the beginning of the file, existing contents remain intact.
c+ Open a file for both reading and writing. Reading and writing will start at the beginning of the file, existing contents remain intact.
e Opens the file with close-on-exec flag enabled for the new file descriptor. Only available in PHP compiled on POSIX.1-2008 conform systems; essential for some multi-threaded system operations.

For more information on the e mode, see O_CLOEXEC's documentation.

Working with dates in PHP? Check out this side dish!

Toggle Dark Mode