Opening a File for Writing, Reading, or Appending

Before you can work with a file, you must first open it for reading, writing, or both. PHP provides the fopen() function for doing so. fopen() requires a string that contains the file path followed by a string containing the mode in which the file is to be opened. The most common modes are read (r), write (w), and append (a). fopen() returns a file resource you'll use later to work with the open file. To open a file for reading, you use the following:

$fp = fopen("test.txt", 'r');

You use the following to open a file for writing:

$fp = fopen("test.txt", 'w');

To open a file for appending (that is, to add data to the end of a file), you use this:

$fp = fopen("test.txt", 'a');

fopen() returns false if the file cannot be opened for any reason. Therefore, it's a good idea to test the function's return value before proceeding to work with it. You can do so with an if statement:

if ($fp = fopen("test.txt", "w")) {
// do something with $fp

Or you can use a logical operator to end execution if an essential file can't be opened:

($fp = fopen("test.txt", "w")) or die ("Couldn't open file, sorry");

If the fopen() function returns true, the rest of the expression won't be parsed, and the die() function (which writes a message to the browser and ends the script) is never reached. Otherwise, the right side of the or operator is parsed and the die() function is called.

Assuming that all is well and you go on to work with your open file, you should remember to close it when you finish. You can do so by calling fclose(), which requires the file resource returned from a successful fopen() call as its argument:


    Part III: Getting Involved with the Code