How to open a file in append mode in PHP?

To write content to a file we can use fwrite() function in PHP. To use fwrite() function to write content to a file, we first need to open the file resource in write or append mode.


Write to a File with PHP

fwrite() function is used to write content to a file when a file is already open in write mode.

Let's take an example, where we will write a couple of movie names to our file movies.txt

$file_name = 'movies.txt';
//opens the file.txt file or implicitly creates the file
$myfile = fopen($file_name, 'w') or die('Cannot open file: '.$file_name); 
$movie_name = "The Man from Earth \n";
// write name to the file
fwrite($myfile, $movie_name);

// lets write another movie name to our file
$movie_name = "SouthPaw \n";
fwrite($myfile, $movie_name);
// close the file
fclose($myfile);

In the code above we wrote two movie names in the file movies.txt. f we open the file, it will look like following:

The Man from Earth SouthPaw

NOTE: When a file is opened in write mode, all the existing data in the file is erased and new data can be written to the file using the fwrite() function.

If we again open the above file to write more content to it, and we open the file in write mode then all the existing content will be erased.


Append data to a File with PHP

If we wish to add more movie names to the file movies.txt then we need to open the file in append mode. Let's take an example and see.

So far we have learned how to open, close, read, and write to a file. However, the ways in which we have written to a file so far have caused the data that was stored in the file to be deleted. If you want to append to a file, that is, add on to the existing data, then you need to open the file in append mode.

If we want to add on to a file we need to open it up in append mode. The code below does just that.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'a');

If we were to write to the file it would begin writing data at the end of the file.

Using the testFile.txt file we created in the File Write lesson , we are going to append on some more data.

PHP Code:

$myFile = "testFile.txt";
$fh = fopen($myFile, 'a') or die("can't open file");
$stringData = "New Stuff 1\n";
fwrite($fh, $stringData);
$stringData = "New Stuff 2\n";
fwrite($fh, $stringData);
fclose($fh);

You should noticed that the way we write data to the file is exactly the same as in the Write lesson. The only thing that is different is that the file pointer is placed at the end of the file in append mode, so all data is added to the end of the file.

The contents of the file testFile.txt would now look like this:

Contents of the testFile.txt File:

Floppy Jalopy
Pointy Pinto
New Stuff 1
New Stuff 2

The above example may not seem very useful, but appending data onto a file is actually used everyday. Almost all web servers have a log of some sort. These various logs keep track of all kinds of information, such as: errors, visitors, and even files that are installed on the machine.

A log is basically used to document events that occur over a period of time, rather than all at once. Logs: a perfect use for append!

If you would rather download the PDF of this tutorial, check out our PHP eBook from the Tizag.com store. Print it out, write all over it, post your favorite lessons all over your wall!

The verbal descriptions take a while to read through to get a feel for the expected results for fopen modes. This csv table can help break it down for quicker understanding to find which mode you are looking for:

Mode,Creates,Reads,Writes,Pointer Starts,Truncates File,Notes,Purpose
r,,y,,beginning,,fails if file doesn't exist,basic read existing file
r+,,y,y,beginning,,fails if file doesn't exist,basic r/w existing file
w,y,,y,beginning+end,y,,"create, erase, write file"
w+,y,y,y,beginning+end,y,,"create, erase, write file with read option"
a,y,,y,end,,,"write from end of file, create if needed"
a+,y,y,y,end,,,"write from end of file, create if needed, with read options"
x,y,,y,beginning,,fails if file exists,"like w, but prevents over-writing an existing file"
x+,y,y,y,beginning,,fails if file exists,"like w+, but prevents over writing an existing file"
c,y,,y,beginning,,,open/create a file for writing without deleting current content
c+,y,y,y,beginning,,,"open/create a file that is read, and then written back down"

If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.

Parameters

filename

Path to the file where to write the data.

data

The data to write. Can be either a string, an array or a stream resource.

If data is a stream resource, the remaining buffer of that stream will be copied to the specified file. This is similar with using stream_copy_to_stream().

You can also specify the data parameter as a single dimension array. This is equivalent to $data1.

$data2

The value of $data2 can be any combination of the following flags, joined with the binary OR ($data4) operator.

Available flagsFlagDescription$data5Search for filename in the include directory. See for more information.FILE_APPENDIf file filename already exists, append the data to the file instead of overwriting it.$data9Acquire an exclusive lock on the file while proceeding to the writing. In other words, a flock() call happens between the fopen() call and the fwrite() call. This is not identical to an fopen() call with mode "x".$flags0

A valid context resource created with stream_context_create().

Return Values

This function returns the number of bytes that were written to the file, or $flags1 on failure.

Warning

This function may return Boolean $flags1, but may also return a non-Boolean value which evaluates to $flags1. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

Examples

Example #1 Simple usage example

$flags4

Example #2 Using flags

$flags5

Notes

Note: This function is binary-safe.

Tip

A URL can be used as a filename with this function if the have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

How do I open file in append mode?

In order to append a new line your existing file, you need to open the file in append mode , by setting "a" or "ab" as the mode. When you open with "a" mode , the write position will always be at the end of the file (an append).

How to append a file in PHP?

PHP Append Text You can append data to a file by using the "a" mode. The "a" mode appends text to the end of the file, while the "w" mode overrides (and erases) the old content of the file.

How do I open a file in PHP?

PHP fopen() function is used to open file or URL and returns resource. The fopen() function accepts two arguments: $filename and $mode. The $filename represents the file to be opended and $mode represents the file mode for example read-only, read-write, write-only etc.

How to read file into string in PHP?

The file_get_contents() reads a file into a string. This function is the preferred way to read the contents of a file into a string. It will use memory mapping techniques, if this is supported by the server, to enhance performance.