Files
Explore how PHP handles file-based data storage and state management. Learn to use PHP functions for reading, writing, and locking files, and understand file handle operations. Discover issues with concurrency and cloud server file storage, plus how to use libraries for seamless cloud file management.
It’s time to look at long-term data stores. The most obvious one is the file system. The logic is simple—if we need to save some data, we put it into a file. That’s what computers do.
Working with files isn’t popular in web applications, but it remains a powerful tool for storing data and passing it between applications.
Using files in PHP
PHP offers many functions for working with files. The complete list is in the PHP Manual.
Here’s a list of the most commonly used functions.
Single operation functions
These are useful when performing a single operation on a file.
- The
file_exists() functionreturnstrueif the requested file exists. If we want to read the file or write to it, it’s better to also check the permissions with theis_readable()oris_writable() functions. They returntrueif the file exists and the script has the necessary permissions for them. - The
file_get_contents() functionreads the whole file into a string. - The
file()function reads the whole file as an array of strings, one string per line. The result still contains line endings. - The
file_put_contents() functionsaves a string into a file. By default, it overwrites the file. We can pass theFILE_APPENDflag as a third argument to append the string to the end of the file instead. - The
readfile() functionpasses the file