You are on page 1of 1

PHP - File Open

In the previous lesson we used the function fopen to create a new file. In this lesson we will be going into
the details of this important function and see what it has to offer.

PHP - Different Ways to Open a File

For many different technical reasons, PHP requires you to specify your intentions when you open a file.
Below are the three basic ways to open a file and the corresponding character that PHP uses.

• Read: 'r'

Open a file for read only use. The file pointer begins at the front of the file.

• Write: 'w'

Open a file for write only use. In addition, the data in the file is erased and you will begin writing data at the
beginning of the file. This is also called truncating a file, which we will talk about more in a later lesson. The file
pointer begins at the start of the file.

• Append: 'a'

Open a file for write only use. However, the data in the file is preserved and you begin will writing data at
the end of the file. The file pointer begins at the end of the file.
A file pointer is PHP's way of remembering its location in a file. When you open a file for reading, the file
pointer begins at the start of the file. This makes sense because you will usually be reading data from the front
of the file.
However, when you open a file for appending, the file pointer is at the end of the file, as you most likely
will be appending data at the end of the file. When you use reading or writing functions they begin at the
location specified by the file pointer.

PHP - Explanation of Different Types of fopen

These three basic ways to open a file have distinct purposes. If you want to get information out of a file,
like search an e-book for the occurrences of "cheese", then you would open the file for read only.
If you wanted to write a new file, or overwrite an existing file, then you would want to open the file with the
"w" option. This would wipe clean all existing data within the file.
If you wanted to add the latest order to your "orders.txt" file, then you would want to open it to append the
data on to the end. This would be the "a" option.

You might also like