mf

Write to Files and Read Files With PHP

In this tutorial, you’ll learn several important functions in PHP which are sufficient for all your basic file reading and writing needs. You’ll learn how to read a file, write to a file, write to a text file, and check if a file exists.

Luckily, PHP provides a lot of functions to read and write data to files. In this tutorial, I’ll show you the easiest ways to read data from a local or remote file and how to use flags to write to files exactly how we want.

Checking if a File Exists

Your very first step when trying to read data from a file or writing something to it should be to check if the file already exists. Trying to read data from a file which does not exist will result in a warning from PHP and will probably crash your code.

The easiest way to check if a file exists is to use the PHP file_exists($filename) function. It will return true if a file or directory with the given $filename exists and false otherwise. This might be obvious, but I would like to point out that $filename doesn’t have to just be the name of a file. It can also be an absolute or relative path. For example, we could use prime_numbers.txt or science/project/periodic_table.txt.

It’s also important to remember that this function will also return false for files which are inaccessible due to safe mode restrictions.

Another function that you can use to check for the existence of a file is is_file(). In contrast to file_exists(), this function will only return true if the specified path points to a file and not a directory.

Making Sure That the File Actually Exists

If the code you are writing performs a lot of file operations on a particular file, you might get incorrect results using the above functions. This is because the results of the execution of both file_exists() and is_file() are cached in order to improve performance. PHP also caches the values returned by other filesystem functions like filesize(), filemtime(), etc.

You can call clearstatcache() to make sure that any information you are accessing for a file is up to date.

This is generally only a problem if the same file is being accessed multiple times in a single script to know its status. Also, the cached data is cleared if you delete the file inside the script using the unlink() function. This basically means that you probably won’t face any caching related problems, but it is still good to know that you can clear the cache in case the information goes stale or if you are getting unexpected results when trying to access information about a file.

Reading Data From a File in PHP

One of the easiest ways to read data from a file in PHP is with the help of the  file_get_contents($filename, $use_include_path, $context, $offset, $maxlen) function. It will simply read the entire file and give it to you in the form of a string. All the parameters except the first one are optional.

The second parameter accepts a boolean value to determine if it should look for a file in the location specified by the include path, which can be set using the set_include_path() function.

You can use the third parameter to specify a bunch of options to refine how the files are accessed. You can use it to specify header values like the Cookies and Host as well as the HTTP method.

The $offset parameter determines the point where reading starts on the original file. Providing a negative value will start counting from the end. The support for negative offsets was only added in PHP 7.1.0. It is worth noting that offset only works with local files and is not supported for remote files.

The file_get_contents() function reads the whole file at once by default. You can change this behavior by providing a value for the $maxlen parameter. The length of characters to be read is counted from the offset value.

This function will return false if it failed to read data from the file you specified. However, it can also return values which evaluate to false, so make sure that you check if it actually returned false using the === operator.

You can use this function to open remote files, but that would be possible only if the value of the allow-url-fopen option in php.ini is true or 1.

Writing Data to a File in PHP

One of the easiest ways to write data to a file in PHP is with the help of the file_put_contents($filename, $data, $flags, $context) function.

The $filename parameter determines the file in which the data will be written. The second parameter is the data that you want to write to the file. Most of the time it will be a string, but it could also be an array or a stream resource. 

Remember that PHP will automatically create a file with the given name for you if it doesn’t already exist. However, it won’t create any directories for you. This means that you can store a file with the name On the Origin of Species [Charles Darwin].txt without any error. However, setting $filename to  Biology/Evolution/On the Origin of Species [Charles Darwin].txt, if Biology/Evolution/ doesn’t already exist, will result in an error.

The $flags parameter determines how the content will be written to a file. It can have any or all of the following three values:

  • FILE_USE_INCLUDE_PATH—This tells PHP to search for the given file name in the include directory.
  • FILE_APPEND—This will tell PHP to append the data you passed to the function to the existing data in the file. It could be useful if you are storing data in a file like a log or a personal diary. Recording new data like temperature or events that happened to you today won’t overwrite something you recorded yesterday.
  • LOCK_EX—This will tell PHP to get a lock on the file before starting to write content into it. It can prevent unexpected things from happening when two different scripts are reading or writing data to the same file. With this particular value, you will get an exclusive lock on the file. You can read more about these locks in the PHP documentation of the flock() function.

This function returns the number of bytes that were written to the file on success and false on failure. However, you must still use the strict equality operator to check if it was successful in writing content to the file. That’s because code that writes 0 bytes to the file will still evaluate to false.

Reading and Writing Data to Files

You can head over to the Project Gutenberg website and try to download files using the  file_get_contents() function. Once you have the data in a string, you can also simply store it in a local file using the file_put_contents() function. The following example will make this clear:

You could save webpages or content from websites like Wikipedia in a similar manner. If you need to make sense of the HTML or parse the HTML content that you just saved locally, you can follow a tutorial like Parsing HTML With PHP Using DiDOM, which will assist you in automatically getting links, image files, or any other such information from the webpage.

Let’s get back to local files now. Consider a situation where you have a bunch of text files and you want to analyze their content to see things like the most common words in them. This could be achieved easily using a bunch of built-in PHP functions.

We converted all the text to lowercase and made the assumption that
every single word breaks at spaces. The text is then converted to an
array using explode() to make it easier to analyze individual words. Surprisingly, the word “evolution” is not used even once in the entire book that gave the theory of evolution its origin. 

This was just an example of automatically analyzing a large amount of text. You could do something similar with any kind of text stored in a file.

Logging Data With FILE_APPEND

One more useful example would be logging information over small periods of time. It could be your exercise routine, weather data, or a bee colony that you are observing. Once you have the data in a string, you can easily store it in a file and append it to existing data using the FILE_APPEND flag with file_put_contents().

Similar code could be used for something like storing Wikipedia’s featured article of the day in a file every day or keeping track of news articles and headlines over the course of weeks or months. All you need to do is write code to scrape the data and then store it using something similar to the above code snippet. A tutorial like Parsing HTML With PHP Using DiDOM can help you with the scraping part.

Instead of writing the text in plain format, you could wrap it in some HTML to make it easier to read in browsers. The possibilities are endless.

Final Thoughts

There are many other ways of reading and writing data to files in PHP. However, file_get_contents() and file_put_contents() will address almost all your basic needs without adding unnecessary complication.

The only time you might face a problem with file_get_contents() is when the file you are reading is very large—like 2GB or more in size. This is because file_get_contents() loads the whole file into memory at once, and there is a good chance of running out of memory with such large files. In that case, you will have to rely on functions like fgets() and fread() to read a small part of the file at once.

Powered by WPeMatico

Leave a Comment

Scroll to Top