Files
Learn how to work with files in PHP and how to avoid common file-related pitfalls.
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() function
returnstrue
if 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 returntrue
if the file exists and the script has the necessary permissions for them. - The
file_get_contents() function
reads 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() function
saves a string into a file. By default, it overwrites the file. We can pass theFILE_APPEND
flag as a third argument to append the string to the end of the file instead. - The
readfile() function
passes the file