What is the difference between fopen modes “r+”, “rw+” and “w+” in PHP?
File handling is a very important part of programming when it comes to making applications. We might require reading input from a file or writing output into a file. File handling in PHP is similar to other programming languages. There are predefined functions that can be used to accomplish the specified task. Check out the Basics of File Handling to know about the functions.
$<variable_name> = fopen(<file source path>,<access mode>)
Difference in the fopen modes r+, rw+ and w+ in PHP
- r+: Opens a file in read and write mode. File pointer starts at the beginning of the file.
- w+: Opens a file in read and write mode. It creates a new file if it does not exist, if it exists, it erases the contents of the file and the file pointer starts from the beginning.
- rw+: Opens a file in read and write mode. File pointer starts at the beginning of the file. This mode does not exists in the PHP documentation but it works well.
Example: For a better understanding, let us observe the parsing function for fopen.
- It checks for the first character of the argument, i.e. mode. Depending upon it being r,w,a or x, corresponding mode is identified.
- It looks for the presence of ‘+’ in the mode argument. If present, it sets the appropriate flags.
Therefore, “r+” and “w+” has a difference in the mode of opening the file and placing the file pointer. The “r+” and “rw+” are the same. PHP only cares that the string starts with “r” and has a “+”. The “w” is ignored in “rw+”. Hence, they work the same.