Login | Contact Us | Site Map | Resources

PHP File & Filesystem Functions

Home > PHP Tutorial > Writing to Files

Writing to Files

In order to write to a file, the file must first be opened with the appropriate mode to allow you to perform the function(s) that you have planned.

After the file is opened we can use the fwrite() function to write to the file. Two parameters are required; the file identification handle and the data to write to the file. The syntax is: fwrite(handle, data);

<?php
  $FileData = "What is the difference between a cat and a comma?\n";
  $FileName = "joke.txt";
  $FileHandle = fopen($FileName, 'w') or die("File Cannot Be Opened or Created");
  fwrite($FileHandle, $FileData);
  fclose($FileHandle);

?>

In the above example we used "w" access to open the file, meaning that it was opened for writing only, and any existing contents of the file were erased. Then we wrote our line of text to the file. The "\n" at the end of the string is a carriage return, or newline character, indicating to the file that the line has ended and the file pointer should jump to the next line down. It will not show up when you read the contents of the file.

By opening the file with another access key, such as "a", we can add data to the end of the file without wiping out the existing contents of the file. This action is also known as "appending".

<?php
  $FileData = "One has the paws before the claws and the other has the clause before the pause.\n";
  $FileName = "joke.txt";
  $FileHandle = fopen($FileName, 'a') or die("File Cannot Be Opened or Created");
  fwrite($FileHandle, $FileData);
  fclose($FileHandle);

?>

Now, if we were to read our "joke.txt" file, we would see the following:

What is the difference between a cat and a comma?
One has the paws before the claws and the other has the clause before the pause.

Summary:

Function Description
fwrite() Binary-Safe File Write