How to Write to a File Using PHP

A Guide on How to Use PHP to Write to a File

With PHP, you're able to open a file on your server and then write to it. Below, I describe not only how to open the file and write data to it, but also how to write over existing data as well as append new information to the end of the text.

Note: If the file does not exist, you can create it. However, if the file already exists, you must chmod it to 777 so it will be writable.

Open the File in PHP

When writing to a file, the first thing you need to do is open the file.

You can use this code to do that:

 <?php 
 $File = "YourFile.txt"; 
 $Handle = fopen($File, 'w');
 ?>

Add Data to the File

To write information to the file, you can use the fwrite command, like this:

 <?php 
 $File = "YourFile.txt"; 
 $Handle = fopen($File, 'w');
 $Data = "Jane Doe\n"; 
 fwrite($Handle, $Data); 
 $Data = "Bilbo Jones\n"; 
 fwrite($Handle, $Data); 
 print "Data Written"; 
 fclose($Handle); 
 ?>

At the end of the file, use fclose to close the file you've been working with. You may also notice I'm using \n at the end of the data strings. The \n servers as a line break, like hitting the enter or return key on your keyboard.

You now have a file called YourFile.txt that contains the data:

Jane Doe
Bilbo Jones

How to Write Over the Data

If you were to run this very same thing again, only using different data, it would erase all of the current information and replace it with whatever you add.

Here's an example:

 <?php 
 $File = "YourFile.txt"; 
 $Handle = fopen($File, 'w');
 $Data = "John Henry\n"; 
 fwrite($Handle, $Data); 
 $Data = "Abigail Yearwood\n"; 
 fwrite($Handle, $Data); 
 print "Data Written"; 
 fclose($Handle); 
 ?>

The file created now contains the data:

John Henry
Abigail Yearwood

How to Add More Data

Let's say you don't want to rewrite over all the information, and instead just add some more names to the end of the list. You can do that by changing the $Handle line.

Currently, it's set to w, which means write only, and only at the beginning of the file. If you change it to a, it will append new data to the file, meaning it will write the information to the end.

 <?php 
 $File = "YourFile.txt"; 
 $Handle = fopen($File, 'a');
 $Data = "Jane Doe\n"; 
 fwrite($Handle, $Data); 
 $Data = "Bilbo Jones\n"; 
 fwrite($Handle, $Data); 
 print "Data Added"; 
 fclose($Handle); 
 ?>

This should add these two names to the end of the file, so that your file now contains four names:

John Henry
Abigail Yearwood
Jane Doe
Bilbo Jones