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 youopen a file. Below are the three basic ways to open a file and the corresponding character that
PHP uses.
- 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 fopen
These three basic ways to open a file have distinct purposes. If you want to get information out of a file, likesearch 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: Advanced
There are additional ways to open a file. Above we stated the standard ways to open a file. However, you can opena 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: Summary
You 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 youcan 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.
No comments:
Post a Comment