How to open a file in PHP?
Reading from and writing to files is one of the most common programming tasks. You can't process data if you don't get it from somewhere (most often a file), and you will usually need to store the result of the processing in something different from the volatile RAM. Again, one of the most common solutions is a file, in which you write the result of the processing. Of course, if you want to be able to read and write to files, you need to know how to open them.
Open a File in PHP as Read-Only
Step 1
Use the 'r' option to open a file as read-only. When a file is opened as read-only, the file pointer is placed in the beginning of the file and you start reading from there.
Step 2
Use the more advanced way, with the 'r+' option, to open a file for reading. The 'r+' option opens a file for both reading from and writing to. As with the 'r' option, the file pointer is at the beginning of the file.
Open a File as Write-Only
Step 1
Use the 'w' option, to open a file as write-only. It is important to note that this option erases the contents of the file, places the pointer in the beginning of the file and starts writing from there.
Step 2
Use the more advanced way, the 'w+' option, to open a file for writing. The 'w+' option opens a file for both reading from and writing to. The difference with 'r+' is that the 'w+' option deletes all information in the file when the file is opened.
Open a File for Appending
Step 1
Use the 'a' option to open the file for writing. The data in the file is not deleted, and the file pointer is placed at the end of the file so that you start writing the new contents after the existing data.
Step 2
Use the more advanced 'a+' option to open the file for appending. The difference with 'r+' is that the file pointer is positioned at the end of the file.