PHP 5 File Open/Read/Close

File handling is an important part of any web application. You often need to open and process a file for different tasks.

File Opening in PHP

fopen() function is used to open a file in PHP. Its required two arguments, first the file name and then file opening mode.

The file may be opened in one of the following modes:

  • 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 clears the contents of the file; or creates a new file if it doesn’t exist
  • w+ Read/Write. Opens and clears the contents of the file; or creates a new file if it doesn’t exist
  • a Append. Opens and writes to the end of the file or creates a new file if it doesn’t exist
  • a+ Read/Append. Preserves file content by writing to the end of the file
  • x Write only. Creates a new file. Returns FALSE and an error if the file already exists
  • x+ Read/Write. Creates a new file. Returns FALSE and an error if the file already exists
  • Example -

    File Reading in PHP

    Once a file is opened using fopen() function then it can be read by a function called fread(). This function requires two arguments. The file pointer and length in bytes of the file must be expressed. The files size can be calculated using the filesize() function which takes the file name as its argument and returns the size of the file in bytes.

    Example -

    Reading a File Line by Line

    The fgets() function is used to read a single line from a file and after a call to this function, the file pointer has moved to the next line.

    Example -