By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

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".)

$fp = fopen('data.txt', 'w');
 fwrite($fp, 'line1' . "\n" . 'line2');

The thing creating the line break is the "\n" in the double quotes, it has to be in double quotes for PHP to convert it to a real line break.

Another way to add more data to the end, is to use fwrite again, this can be useful to know for loops.

$fp = fopen('data.txt', 'w');
 fwrite($fp, 'line1' . "\n");
 fwrite($fp, 'line2');

Write files in PHP With File_put_contents

The file_put_contents function can be used to write files in PHP, it is identical to using the PHP file functions mentioned earlier.

If for example you where to create a guestbook in PHP without using a database, you could start out from script:

$file = 'data.txt';
// Open file to get its content (if any)
$current = file_get_contents($file);
// using (.) we add a new comment
$current .= "Hallo, nice website. Bye!\n";
// Write the content back to the file
file_put_contents($file, $current);

See also

  1. Read Content of Files
  2. Deleting Files and Directories
  3. Copying Files
  4. Renaming Files