[Tutorial] Detailed Guide to fwrite() Operations

In this tutorial I will be deeply explaining in detail the many modes of the PHP function fwrite().  Yes, fwrite() is used to write data to files, however the way it is written to the file changes with each mode.  In each mode, I will explain its purpose, provide an example, and then explain the code within the example.

General Example

Alright, so each mode basically has the same structure when it comes to the programming.  To be technical, the fwrite() function doesn’t change, it is the way fopen() opens your file for writing.

<?php
$fh = fopen('sample.txt', 'w');
fwrite($fh, 'Hello World');
fclose($fh);
?>

So that was just a basic file writing operation.  If the operation was successful, you will have a new file name sample.txt that contains the text ‘Hello World’.  Now I am going to explain each part of the above code.

  • Line 2: fopen() creates a connection to that file.  The first argument is the name of the file you are opening (in our example sample.txt).  The second argument is the mode you are using (which we will discuss in detail below).
  • Line 3: fwrite() will write data to that file.  The first argument defines what opened file from fopen() we will be writing to.  The second argument is the data we are writing to the file (in our example above we are writing the string ‘Hello World’).
  • Line 4: fclose() will close the connection to that file.  The only argument is pointed to the variable used with fopen().

So there you go, you now have a basic file writing script.  Now below we are going to be getting in to a bit more detail on the different modes as well as methods.

You can download this example and find it in the general folder.


Writing To A File Multiple Times

Before we get in to the different modes, lets say you need to make multiple writes using fwrite() to a file, not a problem.  PHP does not limit you to executing fwrite() only once, you can execute it as many times as you wish.  Let’s use the example below to show how that is possible.

<?php
$fh = fopen('sample.txt', 'w');
fwrite($fh, 'I am cooler');
fwrite($fh, ' than you');
fclose($fh);
?>

This will give you the following result in sample.txt:

1
I am cooler than you
I am cooler than you

As you can see, we executed multiple fwrite() functions.  It will just keep adding additional data to your file right where the previous fwrite() left off.  However, each fwrite() must be executed before fclose() is executed for the new data will not be written.  If you would like to have code written on a different line every time, you can use this example below.

<?php
$fh = fopen('sample.txt', 'w');
$string1 = "I am cooler than you\n";
fwrite($fh, $string1);
$string2 = "Not as cool as me\n";
fwrite($fh, $string2);
fclose($fh);
?>

This will give you the following result in sample.txt:

1
2
I am cooler than you
Not as cool as me
I am cooler than you
Not as cool as me

So that is how to perform fwrite() multiple times.  ’\n’ will show that you want to insert a line-break.  This method can even be used in all the examples below, however to keep things simple, I am only going to explain by executing fwrite() once.

You can download these examples and find them in the multiple and multiple2 folders.


Mode ‘w’ – Writing A File

So the first mode we are going to explain is the same one we used in the examples above.  The best way to remember this mode is to say it will write to your existing file (if it exists).  In a brief description, mode ‘w’ will erase all data from the file and write your new data (assuming a file already exists).  If the file does not already exist, it will attempt to create the file and write your data.

Since we have used this mode many times in the examples above, just copy one of the methods above.

Mode ‘a’ – Append A File

This next mode is something we haven’t used in this tutorial just yet.  I am now going to introduce the append or add mode.  Basically, mode ‘a’ will add your new data to the end of the file without deleting the existing data (assuming the file already exists).  If the file does not already exist, it will attempt to create the file and write your data.  Below is an example of an existing sample.txt file we want to add content to.

1
My assignment was due yesterday
My assignment was due yesterday

Now lets use fwrite() to add some extra words to that current file.

<?php
$fh = fopen('sample.txt', 'a');
fwrite($fh, ' so it is now considered late');
fclose($fh);
?>

This will give you the following result in sample.txt:

1
My assignment was due yesterday so it is now considered late
My assignment was due yesterday so it is now considered late

Lets go ahead and break down the PHP code above to explain what we just did.

  • Line 2: We used fopen() to open sample.txt however we used mode ‘a’ in the second argument to put it in to append mode.
  • Line 3: Just like before fwrite() will be writing data to our file, however with mode ‘a’, it only adds data to the end of the file, it doesn’t erase existing data in the file.

So that is the append mode which is great for adding data to existing files.

You can download this example and find it in the append folder.


Mode ‘x’ – Create A File

In the next mode we will be covering, mode ‘x’ which will attempt to create a file and write your data.  This mode does not work with existing files (as it is not intended to).  If you try to perform fopen() on an existing file with mode ‘x’, it will return FALSE and trigger an E_WARNING error.  Below we are going to perform fwrite() using mode ‘x’ and assume sample.txt does not already exist.

<?php
$fh = fopen('sample.txt', 'x');
fwrite($fh, 'This is new data to a new file');
fclose($fh);
?>

This will give you the following result in sample.txt:

1
2
This is new data to a new file
Time to break down the PHP code.
This is new data to a new file
Time to break down the PHP code.
  • Line 2: We used fopen() to open sample.txt however we used mode ‘x’ in the second argument to put in in create file mode.
  • Line 3: We added data in to our new file with fwrite() in mode ‘x’.

So that is the create file mode which is perfect for only wanting to add data to a new file.

You can download this example and find it in the create folder.


Mode ‘c’ – Replace Data (Requires PHP 5.2.6+)

In the final mode I will be covering, mode ‘c’ will write data to a file in a new way we haven’t introduced yet.  Mode ‘c’ will replace data, or as I like to say, it will cover existing data with new data from fwrite() starting at the beginning of the file (if the file already exists).  If the file does not already exist, it will attempt to create the file and write your data just like the previous modes.  Mode ‘c’ will replace any existing data, however will leave a piece of existing data if the length of the new content is less than the existing data.  Below is an example of replacing data in a file starting with the existing data of sample.txt.

1
I hope I do not get deleted when this function is performed
I hope I do not get deleted when this function is performed

Now let’s use fwrite() to replace data.

<?php
$fh = fopen('sample.txt', 'c');
fwrite($fh, '##########');
fclose($fh);
?>

This will give you the following result in sample.txt:

1
##########o not get deleted when this function is performed
##########o not get deleted when this function is performed

Let’s get in to the breakdown of what just happened.

  • Line 2: We used fopen() to open sample.txt however we used mode ‘c’ in the second argument to put in in replace data mode.
  • Line 3: We used fwrite() to write new data that will replace the existing code or become new code if the file doesn’t already exist.

So normally, mode ‘c’ will not be used too often, however if you need to use it, you now know how it works.

You can download this example and find it in the replace folder.


Conclusion

So we covered a lot of information regarding the four available modes of writing data to a file.  There is a fith mode named ‘r+’ but that performs the same as mode ‘w’ so we did not cover it as ‘r’ is primarily intended for reading files.  On top of working with the different modes, we also learned it is possible to execute fwrite() multiple times.

You should now be ready to add to or create new files through PHP.  Please feel free to leave a comment below on what you think or let us know if you have a question.

Download Tutorial Examples

This entry was posted in Main, PHP Tutorials and tagged , , by Brandon Enriquez. Bookmark the permalink.

About Brandon Enriquez

Brandon has been around Prosoft Studio since the very beginning of the company back in the summer of 2007. As the founding member, he has laid out a vision of providing the best professional software and offering methods of teaching others some of his own knowledge. He is very experienced in (X)HTML, CSS, JavaScript, PHP, and SQL programming languages. He is also experienced in Adobe Photoshop for website design and graphic designs such as logos, banners, and other media.