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'
- Write: 'w'
- Append: 'a'
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.
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 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);
0 comments:
Post a Comment