Write or Append data to File in PHP 5

To write content to a file we can use fwrite() function in PHP. To use fwrite() function to write content to a file, we first need to open the file resource in write or append mode.


Write to a File with PHP

fwrite() function is used to write content to a file when a file is already open in write mode.

Let's take an example, where we will write a couple of movie names to our file movies.txt

$file_name = 'movies.txt';
//opens the file.txt file or implicitly creates the file
$myfile = fopen($file_name, 'w') or die('Cannot open file: '.$file_name); 
$movie_name = "The Man from Earth \n";
// write name to the file
fwrite($myfile, $movie_name);

// lets write another movie name to our file
$movie_name = "SouthPaw \n";
fwrite($myfile, $movie_name);
// close the file
fclose($myfile);

In the code above we wrote two movie names in the file movies.txt. f we open the file, it will look like following:

The Man from Earth SouthPaw

NOTE: When a file is opened in write mode, all the existing data in the file is erased and new data can be written to the file using the fwrite() function.

If we again open the above file to write more content to it, and we open the file in write mode then all the existing content will be erased.


Append data to a File with PHP

If we wish to add more movie names to the file movies.txt then we need to open the file in append mode. Let's take an example and see.

$file_name = 'movies.txt';
//opens the file.txt file or implicitly creates the file
$myfile = fopen($file_name, 'a') or die('Cannot open file: '.$file_name); 
$movie_name = "Avengers \n";
// write name to the file
fwrite($myfile, $movie_name);

// lets write another movie name to our file
$movie_name = "Real Steel \n";
fwrite($myfile, $movie_name);
// close the file
fclose($myfile);

The Man from Earth SouthPaw Avengers Real Steel