Opening a File for Writing, Reading, or Appending

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

The fopen() function 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"); 

The fopen() function 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 the $fp resource } 

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:


The resource that became available ($fp) is now unavailable to you.

Sams Teach Yourself PHP MySQL and Apache All in One
Sams Teach Yourself PHP, MySQL and Apache All in One (4th Edition)
ISBN: 067232976X
EAN: 2147483647
Year: 2003
Pages: 333
Authors: Julie Meloni © 2008-2017.
If you may any questions please contact us: