How to Append to a File With PHP

Data is usually stored in a database when people are creating their website. However, sometimes we need to store data in files to make it easier for people to read or modify at a later time.

PHP comes with a lot of functions to read and write data to a file. We can also use a few of them to append data to a file. In this tutorial you’ll learn two different ways of appending data to a file with PHP.

Understanding the file_put_contents() Function

The file_put_contents() function is one of the easiest ways to write data to a file with PHP. It accepts four different parameters that determine its behavior. These parameters are:

  • filename:┬áthe path to the location of the file to which we want to write our data.
  • data: specifies the data that you want to write to the file. It is usually a string but you can also specify an array or a stream resource. The function will automatically implode the contents of a single dimensional array with implode() in order to write the data to a file.
  • flags: controls the behavior of file_put_contents(). There are three different flags that you can set here either by themselves or in combination with other flags. Different flags can be combined using the | operator.
  • context: useful only in providing additional data to PHP when you are reading or accessing content from a stream.

Using file_put_contents() to Append Data to a File with PHP

The default behavior of the function file_put_contents() is to overwrite the contents of a given file with any new data the you provide. This is not desirable when you want to preserve the old data and and new one. In such cases, you can use the FILE_APPEND flag to let PHP know that it should append data at the end of content originally present in the file.

Under some special circumstances, you might be appending data to a file from multiple scripts at the same time. In these situations, it is advisable to get an exclusive lock on the file using the LOCK_EX flag. This can help prevent data corruption or some other unexpected behavior. When you use this flag, other scripts will wait for the current process to complete writing to the file before they append their own data.

Here is an example in which some text is appended to an existing file using file_put_contents().

In the above example, we wrote some strings to a file called canada.txt which contains information about Canada. Both the string were appended at the end of the file one after the other.

Keep in mind the this function will create a file if one doesn’t already exist. However, it won’t create a non-existing directory. So, it might be a good idea to check if a file exists before you start writing to it.

Using fwrite() to Write Data to a File with PHP

Using the file_put_contents() function to write data to a file with PHP is similar to calling fopen(), fwrite() and fclose() in that order. This means that doing multiple write operations on the same file can be inefficient because we are constantly opening and closing the file again and again.

One way to overcome this issue is to call these functions yourself. Just begin by calling fopen() at the start of the write operation. After that, write content to the file as many times as you like with the fwrite() function. In the end, you can simply call fclose() to close the file handle. Let’s discuss each of these steps in detail now.

The fopen() function accepts four different parameters that you can use to tell PHP how it should open a file.

  • filename: the name of file that you want to open.
  • mode: the mode for opening a file can be specified using either one or two characters. Since, we want to open the file and then append some text to it. To append, set the mode with the character a or a+. This will place the file pointer at the end of the file. PHP will also try to create the file if it doesn’t already exist. When files are opened with the a+ mode, you can also read the contents of the file.
  • use_include_path: instructs PHP to look for files inside the specified include path as well. Defaults to false.
  • context: useful only in providing additional data to PHP when you are reading or accessing content from a stream.

Now that the file is open we can use the fwrite() function to add information to the file. fwrite() takes three parameters:

  • resource: this is the resource handle we created earlier with fopen().
  • string: the text that you want to append your file.
  • length: is optional and it is used to set the maximum number of bytes that should be written to the file.

You can close the file handle by using the fclose() function once you have completed all your write operations.

Here is an example that shows you how to use fopen(), fwrite() and fclose() to append data to a file.

Contents of square.txt

In this case, we are writing the square of numbers 1 to 10 in a file called square.txt. We opened it using the fopen() function in a+ mode which means we can also read content from the file as well appending our own content. A new line with the current value of $i and its square is appended to our file with each iteration of the for loop.

There are a few functions like fread() and fgets() that you could use to read whatever is written inside the file. However, you will usually need to use fseek() to place the file pointer at the desired position to read the data as expected. After the loop, we seek to the beginning of the file and read it’s first line with fgets().

Finally, we close the handle to our file by calling the function fclose().

Final Thoughts

In this tutorial, we learned two different methods of appending data to a file with PHP. Using the file_put_contents() function is more convenient for writing data to a file. However, using fwrite() can be more efficient when you have to do multiple write operations on a file. Opening a file with fopen() to append the data also gives you the option to read its contents by moving the file pointer to desired location.

Leave a comment

Your email address will not be published.