1. Computing

Write to a file from PHP

By

1 of 3

Write To A File
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.

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 fwrite 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

  1. About.com
  2. Computing
  3. PHP / MySQL
  4. Advanced PHP
  5. Using PHP to write to file

©2014 About.com. All rights reserved.