9 April 07
Beginner PHP Tutorial 11: Reading from/Writing to Files
PHP’s file functions are often useful, from your small guestbook and counter scripts to full blown web applications such as CMS’ and forums. There are a number of functions, some which read the entire file into memory (useful for scripts that handle a small amount of data) and some which only read a small amount of data into memory at a time (useful for applications handling a great deal of data). There are also the file writing functions, which I’ll be showing you as well and ofcourse the functions for obtaining information about a file and for moving around a file.
Opening the file – fopen()
If you want to handle files in php, in the majority of situations you must know the fopen function. The PHP 5 version of fopen() has 4 parameters, however we will only be dealing with the first two parameters, so that our code is backwards compatible, and also simply because the final two parameters are not important, especially when first learning file management in php.
The first parameter the fopen() function accepts is the name of the file you are trying to open. This can be a remote file, however I am going to discuss this in a later tutorial since things work slightly differently for remote files, so for now just keep the file as a local file. The second paramter the function accepts is the mode in which we wish to open the file. It’s not as complicated as it might sound, just provide “r” if you want to read the file, “w” if you want to write to the file (note that this will empty the contents of the file before you can write to it) and “a” if you wish to append data to the file. There are other modes which can be used so I advise you take a visit to the php manual to discover what these are.
The return value of fopen() is what in php is called a “resource”. This is basically just a reference to an external object that you can store in a variable for things like database queries, images, extension objects and in this situation, a file handle. If you don’t understand what I just said don’t worry, just remember that the return value of the fopen() function must be stored in a variable so that it can be used with other file management functions. Here is an example to help you understand:
$filename = 'file.txt';
$file_handle = fopen($filename, 'r'); //open for reading
Reading from the file – fread()
There are two parameters which you need to provide to fread(), the file handle which was returned by fopen() before and how much you want to read from the file (in bytes). The return value is then simply what is read from the file. In many cases you wish to read the entire file (though you can read as few or as many bytes as you wish with this function), so for this you use another function called filesize(). Basically, this just takes your file name and returns the file size in bytes. Here is an example (based on the previous example):
$filename = 'file.txt';
$file_handle = fopen($filename, 'r'); //open for reading
$data = fread($file_handle, filesize($filename));
So now the variable $data contains all of the data in the file. However there are more memory efficient ways of reading from a file:
Reading a line – fgets()
Instead of reading the entire file (or a big chunk of it, atleast), this function reads from the file line by line. So basically it keeps reading data until it reaches a new line or encounters the end of the file. The first parameter is the file handle returned from fopen() and the second parameter is an amount to read. You can ignore the second parameter if you wish and then each time it will read up to the new line, instead of stopping before. Here’s an example:
$filename = 'file.txt';
$file_handle = fopen($filename, 'r'); //open for reading
$data = '';
while(!feof($file_handle)){
$data .= fgets($file_handle, 1024);
}
You can also see a function in there called feof(). This is very simple, it just checks to see if we have reached the end of the file yet. If we haven’t then we keep on reading, but we have it returns true and we break out of the loop. This function prevents any unneccessary errors.
Writing to a file – fwrite()
This is another very simple function, it just writes the data you give to it into the file. Remember that to use this function the file should be opened in either write mode (“w”) or append mode (“a”). The function once again accepts twi parameters: the file handle from fopen() and the string which you wish to write to the file. There is also a third parameter: the maximum amount of bytes which can be written to the file, though this isn’t particular useful or important. Here’s an example:
$filename = 'file.txt';
$data = 'This is a test'; //data to be written to the file
$file_handle = fopen($filename, 'w'); //open for writing
fwrite($file_handle, $data);
Note that you may see a function called fputs() in other developer’s source code. This is just another name for fwrite, and is completely identical in what it accepts, what is does and what it returns.
Closing the file – fclose()
While in PHP you don’t have to close a file, it’s good practise to do so, especially if you plan on moving to other languages like C/C++ in which the failure to close a file can create big problems. The fclose() function only accepts the file handle. Here’s an example:
$filename = 'file.txt';
$file_handle = fopen($filename, 'r'); //open for writing
fclose($file_handle); //close the file
Reading an entire file – file_get_contents(), file()
In order to read an entire file you can use fread() and pass the filesize to it, but it is far more efficient to use one of php’s built-in functions which are designed to complete a full file read. These two functions are also a great deal faster and easier to use since you don’t have to call fopen() or fclose(). Both functions accept one parameter: the name of the file and both return the data, however it is returned in different ways. file_get_contents() returns the data from the file as a simple string, however file() returns an array, with each member of the array being a line in the file. Here’s an example:
$filename = 'file.txt';
$file_string = file_get_contents($filename); //read the data from the file into a string
$file_array = file($filename); //read the data from the file into an array
$third_line = $file_array<sup><a href="#fn391735561461a1cd275de1">2</a></sup>; //get the third line from the return value of file()
Avoiding errors – file_exists(), is_readable(), is_writable()
These three functions are designed to be used before you try to access a file and are fairly self-explanatory from their names. However, I’ll go over them just so you’re sure how it all works. All three functions only accept one parameter: the file name. file_exists returns whether the file exists (simply really), is_readable returns whether you can read from the file and is_writable returns whether you can write to the file. Here’s some example code:
$filename = 'file.txt';
if(file_exists($filename)){
echo 'The file exists!!<br />';
if(is_readable($filename)){
echo 'You can read from this file!!<br />';
if(is_writable($filename)){
echo 'You can write to this file!!';
}
}
}else{
echo 'The file does not exist.';
}
Deleting a file – unlink()
This function is again very simple, it just takes the file name and deletes the file. Here’s an example:
$filename = 'file.txt';
unlink($filename); //delete the file
The File Pointer – fseek(), ftell()
The file pointer is a concept you need to understand in order to perform fast file reading and writing operations. Basically, the file pointer is the point at which read and write operations occur. So on each fgets() call the file pointer is moved forward ready for the next call. You can move the file pointer around the file as you like using fseek so you can read and write from any point you wish (however, if you are opening the file in append mode then write operations always occur on the end of the file).
fseek() takes three parameters: a file handle returned by fopen(), the position at which you wish to place the file pointer (in bytes) and the third optional parameter which indicates the meaning of the position to PHP. For example, if you pass the SEEK_SET flag (which is the default) into the third parameter then the position is from the beginning of the file. If you pass the SEEK_CUR flag into the third parameter then the position is based upon the current position. And if you use SEEK_END then the position is from the end of the file (you need to give a negative position value to move to a position before the end of the file). Here’s an example:
$filename = 'file.txt';
$file_handle = fopen($filename, 'r'); //open file for reading
fseek($file_handle, 8, SEEK_CUR); //move 8 bytes forward from the current position
$data = fread($file_handle, 100); //read 100 bytes from the file
The other function for managing the file pointer is ftell(), which very simply takes the file handle and returns the position of the file pointer from the start of the file. Here’s an example which gets the length of an opened file:
$filename = 'file.txt';
$file_handle = fopen($filename, 'r'); //open file for reading
fseek($file_handle, 0, SEEK_END); //move to the end of the file
$len = ftell($file_handle); //get the current position - which will be the length of the file in bytes
Other Useful File Functions
There are many more useful file functions that you should have a look at yourself:
- tmpfile()
- touch()
- copy()
- readfile()
- fpassthru()
- ftruncate()
- filemtime()
- flock()
- fscanf()
- rename()
- ...and the list goes on…
The best way to get details of these functions is to head up to the php manual and have a good read, most functions are fairly simple to understand. Now that you know the main php file management functions you’ll be able to write your own simple scripts to open files, read from them, write to them, delete them etc. With some further reading from the php manual you should know all you need to know for managing files in php.

