An In-Depth Overview of File Operations in PHP

In this Tuts+ Premium tutorial we will learn how to work with file operations using PHP. This is one of the most fundamental subjects of server side programming in general. Files are used in web applications of all sizes. So let's learn how to read, write, create, move, copy, delete files and more.

Screencast Preview

Copying, Moving and Deleting Files

We are going to start learning with these operations first, because they are very simple one liners, and they do not involve dealing with file pointers.

Deleting a File

There is no such function as "delete". Here we call the "unlink" function.

$file = "test.txt";
unlink($file, $newfile);

Opening and Reading a File

Now it is time to start dealing with some file pointers. There is more than one way of reading the contents of a file in PHP, but we are going to start with the most basic method first. Later in the article we will learn about the alternative methods.

There are three file functions we will use here: fopen, fread and fclose.

When opening the file, we include a second parameter, which determines the type of access. In this case "r" stands for "read only". There are other types that we need to use for writing and appending that we will cover later in the article.

The second important thing to pay attention to is the second parameter in the fread function. This determines the length of the data (in bytes) to read from the file. To read the entire contents of the file, we need to pass the total file size. The filesize function does the trick:

Full Screencast

Understanding File Pointers

Since we started working with file pointers, let's take a moment and try to understand them better.

A file pointer, also known as a file "handle", is a variable that refers to a file. The exact value of this variable is unimportant; all we need to know is that it points to a specific file. The pointer is usually obtained by opening a file. In PHP we use the fopen function.

Even though PHP has an excellent garbage collector that closes all open file pointers at the end of a scripts execution, it is considered a good practice to close them manually using the fclose function.

$fp = fopen($file, 'r');
// ...
// always close files
fclose($fp);

Position in a File

The file pointer actually does more than just pointing to a file. It also points to a specific position inside that file. In most cases, when you open a file, the file pointer points to the beginning (or position 0) in that file. We will cover this concept in more detail when we talk about "seeking" later in the article.

Writing To a File

Just like reading files, there is more than one way of writing to a file. First we will see the basic way, and later in the article we will look at alternatives.

The following code writes the contents of the $data variable into the test.txt file.

This time we used a different flag for opening the file. The "w" flag opens the file for writing, and overwrites all existing data in the file. If there was anything in the test.txt file, it will be replaced with the string in $data.

The fwrite function was very simple, we just passed the file pointer and the data to be written to the file. There is an optional third parameter that determines the length of data to be written:

File Access Modes

Now that we are familiar with the reading, writing and seeking concepts, it is time better understand the different file access modes. When opening a file with the fopen function, the second parameter must be provided, which is the file access mode. There is a table in the PHP manual describing them:

By looking at these, you can see that we have more options than we talked about so far. Here are some important factors to consider about picking the right option:

Opening with 'r+' will fail, if the file is not writable, even if you just want to read and not write to it.

Both 'w' and 'w+' will completely delete the contents of an existing file as soon as you open it. If you intend to add data, you need to use 'a' or 'a+'.

If you want to create new files, and also prevent accidentally overwriting and existing file, use 'x' or 'x+'.

When working with binary files, such as images, add the letter 'b' after the mode. For example: 'rb' or 'r+b'

Getting File Information

There are many pieces of information we can obtain about a file besides just its contents (size, last access time, modify time etc...) The main function used for this is stat.

filesize, fileatime, filemtime

These are alternatives to the stat function for getting file information.

$file = "test.txt";
// gets the file size
echo filesize($file);
// gets the last time the file was modified
echo filemtime($file);
// gets the last time the file accessed
echo fileatime($file);

File Permissions

Unix-like systems have a quite detailed file permissions standard. Windows systems have it a little simpler. The whole subject of file permissions can be lengthy and a whole separate article can be written on it. So instead, we will only look at two simple concepts of file permissions: being "readable", and being "writable".

Checking for Permissions

Your script may or may not have read and/or write access to a file due to various reasons. Before attempting to open a file for reading or writing, it is wise to check if you have permission to do so:

Using Loops for Big Files

Last thing we are going to talk about is a quick tip for handling big files. This has some performance implications.

Easiest way to read and output a file is this:

$file = "test.txt";
echo file_get_contents($file);

But that causes the entire contents of the file to be loaded into the memory. It will persist as long as it is being downloaded by the web surfer. If you have multiple people downloading files at the same time, this can consume your web servers memory very quickly.

A better idea for handling this would be to use a loop to read only small chunks of the file at a time. For the loop condition we will utilize the feof function:

The code above will only load 4kb of data at once into the memory, and this will greatly reduce the memory usage for big file outputs. The feof function returns true when we reach the end of the file, and this breaks out of the loop.

Burak Guzel is a full time PHP Web Developer living in Arizona, originally from Istanbul, Turkey. He has a bachelors degree in Computer Science and Engineering from The Ohio State University. He has over 8 years of experience with PHP and MySQL. You can read more of his articles on his website at PHPandStuff.com and follow him on Twitter here.