Create and Write to Files With PHP

PHP Tutorial on how to create and write to local files using PHP.

Edited: 2014-12-28 04:07

This Tutorial in PHP shows how to create and write to files locally. Writing and creating files is done with a combination of the fopen and fwrite functions. To create or write to a file, it has to first be opened with fopen using the w mode.

The w mode that we are using in this PHP Tutorial will open up the file for writing only, the pointer will be placed at the beginning of the file – if the file already exists, its existing content will be erased and replaced with the new content. Also, if the file doesn't exist, it will be created automatically – this is very useful, as it avoids having to check for file existence before writing to a file.

Perhaps an even easier way to write to files, is to use file_put_contents – this is the equivalent of using: fopen, fwrite and fclose.

Writing Files With PHP fwrite

The following example script will write two lines to a file. The fopen function creates and opens the file for writing, assigns it to a filehandle (the file handle is just a simple variable "$fp".)