Before we can read, modify or delete the contents of the files, we need to open them in PHP. This opening process should not be understood in the sense of reading. Before starting the necessary operations, it means to open the file in the sense of providing the first access and connection.

We will do this access with the fopen() function. This function works with two parameters. In the first parameter, we enter the file path that we will access, and in the second parameter, we enter the mode that will indicate what we are accessing the file for.

There are 8 modes to specify what we want to enter the files for. Let’s write in the table with their explanations:

Mode Description
r Opens the file for reading. (read)
r+ Opens the file for both reading and writing. (read)
w Opens the file for writing. Deletes existing content (write)
w+ Opens the file for both writing and reading. Deletes existing content, rewrites it. (write)
a Opens the file for writing. Does not delete existing content, adds it to the end. (append)
a+ Opens the file for both writing and reading. Does not delete existing content, adds it to the end. (append)
x Creates the file and opens it for writing. Returns FALSE if the file already exists.
x+ Creates the file, opens it for writing and reading. Returns FALSE if the file already exists.

Now, with these above file modes, we can treat how we want for the file.

After performing the necessary operations with the files, we must not forget to close them. If we do not close it, we may encounter problems accessing the next file. We will use the fclose() function to close the files.

This function works with a parameter and closes the file we opened. We write the variable of the file we opened with fopen in its parameter.

<?php
$file = fopen('hello.txt', 'r');
fclose($file);

In the above example, we opened the hello.txt file for reading and provided the first access, and then closed it immediately. Do not think that we reach the content just by providing access. After providing the connection, we will perform the necessary operations using other read and write functions.