home email about rss

Writing to a File in PHP

First and foremost MAKE SURE YOU HAVE WRITE PERMISSIONS ENABLED ON THE FILE/DIR YOU WISH TO WRITE TO. Chmod 755, no more. Ok, so the code is similar to reading from a text file with a few different lines:

<?php
$filename = 'test.txt';
$fp = fopen($filename, "w");
$string = "w00t\nHello World";
$write = fputs($fp, $string);
fclose($fp);
?>

This time we are opening the file for writing using the letter “w”

$fp = fopen($filename, "w");

We have assigned the value “w00t\nHello World” to the variable $string, which is then written to the file using the following fputs() command:

$string = "w00t\nhello world";
$write = fputs($fp, $string);

NOTE: The “\n” simply means insert a newline, so in the text file it’ll look like this:

w00t
Hello World

Again, CLOSE the file before doing anything else:

fclose($fp);

And we’re done! You’ve successfully written and read files using PHP, as well as learned a few basics about PHP (hopefully!). There are other ‘flags’ you can use with the fopen() command REMEMBER THIS BIT? fopen($filename, “w”);. The “w” is a flag. They are as follows:

  • r‘ - Open for reading only; place the file pointer at the beginning of the file.
  • r+‘ - Open for reading and writing; place the file pointer at the beginning of the file.
  • w‘ - Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
  • w+‘ - Open for reading and writing; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
  • a‘ - Open for writing only; place the file pointer at the end of the file. If the file does not exist, attempt to create it.
  • a+‘ - Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it.

Similar Posts: