Category Archives: PHP-file mode

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.
Summary

r Opens the file for reading only, and begin reading at the start of the file
r+ Opens the file for reading and writing, beginning at the start of the file
w Opens the file for writing only, and deletes everything in the file. If the file doesn’t exist, PHP will also try to create it.
w+ Opens the file for reading and writing and deletes everything within the file. If the file doesn’t exist, PHP will so try to create it.
a Open the file for writing only, beginning at the end of the file
a+ Open the file for reading and writing, beginning at the end of the file.