Skip to content
Related Articles

Related Articles

What is the difference between fopen modes “r+”, “rw+” and “w+” in PHP?
  • Last Updated : 07 May, 2020

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[0]. 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.





PHPAPI int php_stream_parse_fopen_modes(const char *mode, int *open_flags)
    int flags;
    switch (mode[0]) {
        case 'r':
            flags = 0;
        case 'w':
            flags = O_TRUNC|O_CREAT;
        case 'a':
            flags = O_CREAT|O_APPEND;
        case 'x':
            flags = O_CREAT|O_EXCL;
        case 'c':
            flags = O_CREAT;
            /* unknown mode */
            return FAILURE;
    if (strchr(mode, '+')) {
        flags |= O_RDWR;
    } else if (flags) {
        flags |= O_WRONLY;
    } else {
        flags |= O_RDONLY;
#if defined(O_CLOEXEC)
    if (strchr(mode, 'e')) {
        flags |= O_CLOEXEC;
#if defined(O_NONBLOCK)
    if (strchr(mode, 'n')) {
        flags |= O_NONBLOCK;
#if defined(_O_TEXT) && defined(O_BINARY)
    if (strchr(mode, 't')) {
        flags |= _O_TEXT;
    } else {
        flags |= O_BINARY;
    *open_flags = flags;
    return SUCCESS;


My Personal Notes arrow_drop_up
Recommended Articles
Page :