PHP - Opening a File with fopen()

Introduction

The fopen() function opens a file and returns a file handle associated with the file.

The first argument passed to fopen() sets the name of the file, and the second argument specifies the open mode.

For example:

$handle = fopen("./data.txt","r" );

If the first argument is just a filename "data.txt", PHP will look for the file in the current directory.

It can be a relative "./data.txt" or absolute "/myfiles/data.txt" ) path to a file.

You can even specify a file on a remote Web or FTP server, as these examples show:

$handle = fopen("http://www.example.com/index.html" ,"r" );
$handle = fopen("ftp://ftp.example.com/pub/index.txt" ,"r" );

Usually, the current directory is the same directory as the script, but you can change this by calling chdir().

Open Mode

The second argument to fopen() tells PHP how you're going to use the file.

It can take one of the following string values:

Value Open the file for
r reading only. The file pointer is placed at the beginning of the file.
r+reading and writing. The file pointer is placed at the beginning of the file.
w writing only. Any existing content will be lost. If the file does not exist, PHP attempts to create it.
w+reading and writing. Any existing file content will be lost. If the file does not exist, PHP attempts to create it.
a appending only. Data is written to the end of an existing file. If the file does not exist, PHP attempts to create it.
a+reading and appending. Data is written to the end of an existing file. If the file does not exist, PHP attempts to create it.

You can append the value b to the argument to open file as a binary file. This is the default setting.

You can append t to treat the file like a text file.

For example, to open a file in binary mode use:

$handle = fopen("data.txt" ,"rb" );

If there was a problem opening the file, fopen() returns false rather than a file handle resource.

For example:

if (!($handle = fopen("./data.txt" ,"r" ))) die("Cannot open the file" );

Closing a File with fclose()

You can close a file using fclose(), passing in the open file's handle as a single argument, like this:

fclose($handle);

Related Topic