PHP File Write

Using the fopen() function, we are able to open a file, assigning ourselves certain permissions to that file. However, we use the fwrite() function to properly write data to any given file.

As with any other file manipulation function, we must first open the file before we can write to it. (For more information, see fopen)


$file=fopen("myfile.txt","w") or die("myfile.txt does not exist!");

Notice that we are opening the file using the (w) write only mode.

Taking the information we learned from fopen, we understand that the write only mode will open and clear the contents of our file, or it will create a new file if it doesn’t already exist.

Now that the file is open, we can write some data to it:


$data = "My file now has some data.";
fwrite($file, $data);

What we just did was assign the string “My file now has some data.” with the variable name of $data.

We then used the fwrite function to write the contents of the $data variable to the file ($file) as was already specified, being “myfile.txt”.

We can use the same procedure to write more than one line of data to the same file:


$data = "My file now has some data.\n";
fwrite($file, $data);
$data = "Now it has even more.\n";
fwrite($file, $data);

We just did the same thing as before, only we repeated it twice and added a carriaged return (\n), which is the same as pressing the “Enter” key on your keyboard, to the end of each line. (For more information, see PHP syntax.

Our end result would be a file named “myfile.txt” with the following contents:

My file now has some data.
Now it has even more.

Always remember to use the fclose function to close the file once you’re done writing to it:


fclose($file);

End Result

Let’s put it all together now leaving out all the comments I’ve left above:


$file=fopen("myfile.txt","w") or die("myfile.txt does not exist!");

$data = "My file now has some data.\n";
fwrite($file, $data);
$data = "Now it has even more.\n";
fwrite($file, $data);

fclose($file);

Reopening The File

As we learn using the fopen function, if we open the file again using the “w” (write only) mode, we will erase all of the contents of myfile.txt and overwrite them with any new contents we insert.

We can control whether to save the previous data and add our new data to the file (see File Append), or to open it as demonstrated in this lesson and erase all its contents.

For a complete list of the different modes you can use when opening a file, see fopen().