Write to a File Using PHP

php file format

 mmustafabozdemir/Getty Images

From PHP you are able to open up a file on your server and write to it. If the file does not exist we can create it, however, if the file already exists you must chmod it to 777 so it will be writable.

01
of 03

Writing to a File

When writing to a file, the first thing you need to do is to open up the file. We do that with this code:

 <?php 

 $File = "YourFile.txt"; 

 $Handle = fopen($File, 'w');

 ?>

Now we can use the command to add data to our file. We would do this as shown below:

 <?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, we use ​fclose to close the file we have been working with. You may also notice we are using \n at the end of our 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

02
of 03

Rewrite Data

If we were to run this very same thing again only using different data, it would erase all of our current data, and replace it with the new data. Here is 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 we created, YourFile.txt, now contains this data:
John Henry
Abigail Yearwood

03
of 03

Adding To Data

Let's say that we don't want to rewrite over all of our data. Instead, we just want to add more names to the end of our list. We would do that by changing our $Handle line. Currently, it is set to w which means write-only, beginning of the file. If we change this to a, it will append the file. This means it will write to the end of the file. Here is an example:

 <?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 our file now contains four names:
John Henry
Abigail Yearwood
Jane Doe
Bilbo Jones

Format
mla apa chicago
Your Citation
Bradley, Angela. "Write to a File Using PHP." ThoughtCo, Aug. 28, 2020, thoughtco.com/write-to-a-file-from-php-2693790. Bradley, Angela. (2020, August 28). Write to a File Using PHP. Retrieved from https://www.thoughtco.com/write-to-a-file-from-php-2693790 Bradley, Angela. "Write to a File Using PHP." ThoughtCo. https://www.thoughtco.com/write-to-a-file-from-php-2693790 (accessed March 28, 2024).