Depending on what we want to do with a file, the file handling process can vary. However, the first and last steps will always be the same; we will open the file first, and close it when we’re finished.

Let’s first take a look at how to open a file. If for instance we wanted to open a file called "my-file.txt", here’s how we could open it:

fopen("my-file.txt", "r");

In PHP, we can use the fopen (short for “file open”) function to open a file. Let’s break down the syntax in the above example:

  • The first argument is "my-file.txt"; the name of the file we’d like to open. This assumes my-file.txt is located in the same directory as the PHP script opening it, but if the file is located elsewhere, we can provide the path to the file (e.g., ../some-location/my-file.txt).

  • The second argument is the mode, "r". The mode describes the type of access we want for the file we’re opening. In this case, the r stands for read mode. This means we can read the file from our code, but if we wanted to write to the file, we’d need to use a different mode.

There are 11 total modes that can be used with fopen. We’ll cover a few of them in this lesson.

It is important to note that the fopen function returns a reference to the opened file, called a file pointer. This allows us to interact with the file from other parts of our code. However, in order to use the file pointer, we’ll need to assign it to a variable.

Let’s update our code from earlier to include this crucial component:

$file = fopen("my-file.txt", "r");

In the above code, we’re assigning the result of fopen (a reference to our opened file, my-file.txt) to a variable called $file. We’ll use this variable to access the file from our code and to close the file when we’re done.

Lastly, as we have already alluded to, whenever we’re finished with an open file, we’ll need to close it. By assigning the file pointer to a variable, we can easily close the file using the fclose function. Here’s how we can use it:


Here, we used the fclose function to close the file referenced by the $file variable, my-file.txt. This is important because it safely disconnects the file from our application, preventing errors such as unsaved changes and data corruption. Just imagine what would happen if we never closed any of our files! Our computer’s memory (every time we open a file, we use a tiny bit of it) would eventually overload and our computer’s performance would grind to a halt. While it is not likely to happen with modern computer systems, as a best practice, always use fclose to close any files that aren’t in active use.

Let’s now practice using fopen and fclose to get a grasp of the basics of file handling.



Open info.txt in read mode. Store the file pointer as $info_file.


Close info.txt.

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?