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 FileFor 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
- Read: 'r'
- Write: 'w'
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'
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 fopenThese 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.
PHP - File Open: AdvancedThere are additional ways to open a file. Above we stated the standard ways to open a file. However, you can open
a file in such a way that reading and writing is allowable! This combination is done by placing a plus sign "+" after the file mode character.
- Read/Write: 'r+'
- Write/Read: 'w+'
- Append: 'a+'
PHP - File Open: Cookie Cutter
Below is the correct form for opening a file with PHP. Replace the (X) with
one of the options above (i.e. r, w, a, etc).
Pseudo PHP Code:
$ourFileName = "testFile.txt"; $fh = fopen($ourFileName, 'X') or die("Can't open file"); fclose($fh);
PHP - File Open: SummaryYou can open a file in many different ways. You can delete everything and begin writing on a clean slate, you can add to existing data, and you
can simply read information from a file. In later lessons we will go into greater detail on how each of these different ways to open a file is used
in the real world and give some helpful examples.