1. Home
  2. Computing & Technology
  3. PHP / MySQL

Write to a file from PHP

By Angela Bradley, About.com

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

Index: Write to a file from PHP

  1. Write To A File
  2. Rewrite Data
  3. Adding To Data

1 of 3

Explore PHP / MySQL

More from About.com

  1. Home
  2. Computing & Technology
  3. PHP / MySQL
  4. Advanced PHP
  5. Write File - PHP Write File - PHP Write to File

©2008 About.com, a part of The New York Times Company.

All rights reserved.