Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

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 this. fopen() requires a string containing 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 will later use to work with the open file. To open a file for reading, you would use the following:

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

You would 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 would use this:

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

fopen() returns false if the file cannot be opened for any reason. It is a good idea, therefore, to test the function's return value before proceeding to work with it. You can do this 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) will never be reached. Otherwise, the right-hand side of the or operator will be parsed, and the die() function will be called.

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

fclose( $fp );
  • + Share This
  • 🔖 Save To Your Account