Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP fopen() Function

PHP fopen() Function


PHP Filesystem Reference Manual Complete PHP Filesystem Reference Manual


Definition and Usage

The fopen() function opens a file or URL.

If fopen() fails, it returns FALSE with an error message. You can suppress the error output by prefixing the function name with '@'.

Syntax

fopen(filename,mode,include_path,context)

Parameters Description
filename Required. Specifies the file or URL to open.
mode Required. Specifies the type of access you require to the file/stream.

Possible values:

  • "r" (Open for reading only; place the file pointer at the beginning of the file)
  • "r+" (Open for reading and writing; place the file pointer at the beginning of the file)
  • "w" (Open for writing only; clear the file contents, or attempt to create the file if it does not exist)
  • "w+" (Open for reading and writing; clear the file contents, or attempt to create the file if it does not exist)
  • "a" (Open for writing only; place the file pointer at the end of the file for writing, or attempt to create the file if it does not exist)
  • "a+" (Open for reading and writing; preserve the file contents by placing the file pointer at the end of the file for writing)
  • "x" (Create a new file and open it for writing; if the file already exists, return FALSE and an error)
  • "x+" (Create a new file and open it for reading and writing; if the file already exists, return FALSE and an error)
  • | | include_path | Optional. Set this parameter to '1' if you also want to search for the file in the include_path (in php.ini). | | context | Optional. Specifies the context of the file handle. A context is a set of options that can modify the behavior of a stream. |

    Tips and Notes

    **Note:** When writing a text file, make sure you use the correct line ending character! On Unix systems, the line ending is \n; on Windows systems, it is \r\n; on Macintosh systems, it is \r. Windows provides a text conversion flag "t" that transparently converts \n to \r\n. You can also use "b" to force binary mode, so no conversion of data occurs. To use these flags, use "b" or "t" as the last character of the mode parameter.


    Example


    PHP Filesystem Reference Manual Complete PHP Filesystem Reference Manual