[ Team LiB ] Previous Section Next Section

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. Therefore, you should test the function's return value before working 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 isn't 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() statement is executed.

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 );


If you are writing a binary file on a Windows system, you should add a 'b' flag to your fopen() mode argument. This tells the operating system that you are working with a binary file and that line endings should not be translated. You can write files in this way:

$fp = fopen( "binary_file", "wb" );

and read them like this:

$fp = fopen( "binary_file", "rb" );


We often store the resource returned by fopen() in a variable called $fp. This is a convention only. fp stands for file pointer. You might want to use a more descriptive variable name in your projects. As always, it's a matter of balancing brevity and clarity.

    [ Team LiB ] Previous Section Next Section