PHP: Write and append to files with file_put_contents

Posted in PHP -

The PHP file_put_contents() function is a useful shortcut for dumping a string into a file (compared with using fopen, fputs etc). By default it will create a new file if it does not exist, or overwrite the file if it does exist. Recently I re-read the documentation for this function and discovered it is also possible to append to a file with file_put_contents.

Writing to a new file / overwriting an existing file

Pass a filename and the string to write to the file (an array containing a stream can also be passed but that's beyond the scope of this post) and either a new file will be created containing the contents of the string or an existing one will be overwritten with the contents of the string.

file_put_contents('/path/to/filename', $data);

Note that the directory you wish to write the file to must exist and be writable to as the user the script is running as. If overwriting an existing file then that file must be writable as the user the script is running as.

Appending to an existing file

As I discovered recently, it is also possible to append to an existing file using file_put_contents. The function can take a third parameter containing a list of flags joined with a binary OR operator.

To append to a file, pass the FILE_APPEND flag like so:

file_put_contents('/path/to/filename', $data, FILE_APPEND);

As with overwriting an existing file, the file must be writable as the user the script is running as.



Related posts:


Comments