PHP fopen() Function

PHP fopen Function


Definition :

The PHP fopen() function opens a file or an URL. The function binds a named resource, specified by filename, to a stream. The mode parameter is used to specify the type of access required with the stream. The function returns a file pointer resource on success, or false on failure. The error output can be hidden by adding an '@' in front of the function name.

Syntax

  fopen(filenamemodeinclude_pathcontext)

Parameter Values
Parameter 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" - Read only. Starts at the beginning of the file
  • "r+" - Read/Write. Starts at the beginning of the file
  • "w" - Write only. Opens and truncates the file; or creates a new file if it doesn't exist. Place file pointer at the beginning of the file
  • "w+" - Read/Write. Opens and truncates the file; or creates a new file if it doesn't exist. Place file pointer at the beginning of the file
  • "a" - Write only. Opens and writes to the end of the file or creates a new file if it doesn't exist
  • "a+" - Read/Write. Preserves file content by writing to the end of the file
  • "x" - Write only. Creates a new file. Returns FALSE and an error if file already exists
  • "x+" - Read/Write. Creates a new file. Returns FALSE and an error if file already exists
  • "c" - Write only. Opens the file; or creates a new file if it doesn't exist. Place file pointer at the beginning of the file
  • "c+" - Read/Write. Opens the file; or creates a new file if it doesn't exist. Place file pointer at the beginning of the file
  • "e" - Only available in PHP compiled on POSIX.1-2008 conform systems.
include_path Optional. Set this parameter to '1' if you want to search for the file in the include_path (in php.ini) as well
context Optional. Specifies the context of the file handle. Context is a set of options that can modify the behavior of a stream

Lets assume that we have a file called demo.txt. This file contains following content:

This is a test file.
It contains dummy content.

In the example below, the file is opened using fopen() function with 'r' mode. This places the file pointer at the beginning of the file. After performing the reading operation, it is closed using fclose() function.

Output : 

This is a test file.
It contains dummy content.