Make your own free website on

Visit the Official PHP Website

Search this Site

PHP Programming

By James N Hitz

Opening and Closing files

To open a file we use the fopen() function. This function accepts the filename as an argument (in simple English, this means that it expects you to specify the filename within the bracket):

fopen() also requires that you specify the open mode after the filename. The mode could be one of these:

'r'   - read only.   file pointer at start of file
'r+'  - read/write.  pointer at start of file
'w'   - write only.  truncate file, pointer at beginning, attempt creation
'w+'  - read/write.  truncate file, pointer at beginning, attempt creation
'a'   - write only.  pointer at end of file, attempt creation
'a+'  - read/write.  pointer at end of file, attempt creation

All these will be explained later.

fopen() returns (gives back) a file handle. This is an integer representing special ID that is used to refer to the file. All through this lesson (and others after this) we'll use the term "filehandle", "file_handle" or sometimes "$filehandle" inter-changeably to refer to a unique system-generated ID for referencing opened files. We refer to it just like it is a normal variable:

So the syntax for using fopen() is:

$filehandle = fopen("file_to_open","mode");

Remember the "file to open" argument could be the actual filename or a string variable containing the filename.

Where the file name is specified on a Windows system (directly or in the variable), you'll have to specify the filename using fore-slashes(/) e.g.

 $filehandle = fopen("c:/httpd/www/list.txt" 'r');

...or use double backslashes(\\):

 $filehandle = fopen("c:\\httpd\\www\\list.txt" 'r');

Come on it's Bill Gates... not me! But leave the poor (rich) guy alone. He's got enough trouble right now.

When you want to close a file, you use fclose() with the filehandle of a previously opened file:


Example: open and close a file

<HTML><HEAD><TITLE>PHP file System functions</Title>
</HEAD><BODY bgcolor="black" text="white">

     $file2open = "/www/home/list.txt";
     $listfile = fopen($file2open, 'r');


An accomplished PHP-monger will look at the above code sadly and shake their head.


<< Opening and Closing Files | Assumptions >>

JamHitz Productions