Categories
PHP

Opening and Closing Files

fopen() is the function to open a file on disk as a resource. This function gives you access to any file and its contents. When you open a file, you can open it for several purposes, for example, reading, writing, and appending (adding information to the end of the file).

For most file system functions, the files have to be opened first. The function fopen() does exactly this and returns a file handle, a pointer to the file. This file handle can then be used in subsequent functions to, for instance, read information from a file or write to it.

<?php
 //Syntax
 fopen(
    string $filename,
    string $mode,
    bool $use_include_path = false,
    ?resource $context = null
 ): resource|false 

fopen() expects at least two parameters:

  • $filename – The name of the file
  • $mode – The file mode to use when accessing the file

The optional parameters:

  • $use_include_path – The optional third parameter can be set to ‘1’ or true if you want to search for the file in the include_path, too.
  • $contextA context stream resource.

Example: Opening and Closing Files

The fopen function returns a file pointer resource on success or false on failure and the fclose function returns true on success or false on failure:

<?php
 $fp = fopen('file.txt', 'r');
 if ($fp === false)
  die ('Error opening file');

 echo 'File opened.';
 $cl = fclose($fp);
 if ($cl)
  echo 'File closed.';
 else
  echo 'Error closing file.';

The fclose() function takes one parameter that must be a valid file resource, and points to a file successfully opened by fopen() ( or fsockopen()).

As soon as a file is not used anymore, it should be closed. PHP automatically closes all open files upon the termination of the script; however, to use the system resources as efficiently as possible, files should be closed as early as possible to free up memory and speed up the system. For this, use fclose() and provide the file handle as a parameter.

To avoid any mistakes when trying to access non-existing files, you can use the function file_exists(), which returns regardless of whether a given filename exists.

<?php
 $file = 'file.txt';
 if ( file_exists($file) ) {
  $fp = fopen($file, 'r');
  //
 }

fopen() modes

fopen() function has the following modes for the file to be used once it’s open:

  • r : one read-only mode
  • a, c, w, x : four write-only modes
  • a+, c+, r+, w+, x+ : five read/write modes.

These modes give you control over whether to overwrite the existing content or append new data. The following table describes the detail of each mode:

ModeDescription
aOpen the file to append (write) data; create it if it doesn’t exist.
a+As mode a, but additionally with read access to the file.
cOpen the file to write data, preserving its contents; but the internal pointer is placed at the beginning of the file. Creates a file if it doesn’t already exist.
Use this mode is to lock the file with flock() before modifying it.
c+As mode c, but in addition with write access to the file.
rOpen the file to read the data.
r+As mode r, but in addition with write access to the file.
wOpen the file to write data, erasing its contents; create it if it doesn’t exist.
w+As mode w, but in addition with read access to the file.
xCreate a file to write data; send E_WARNING if it already exists.
x+As mode x, but in addition with read access to the file
Read/write modes used with fopen()

Binary file modifier

There are other modifiers, as well. As of PHP 4.3.2, PHP does a really good job determining whether a file is a text file or a binary file and translates characters appropriately. If you append b to a file mode, you force PHP to open a file as a binary file; for instance, the file mode rb opens a file for reading in binary mode:

<?php
 $fp = fopen ( 'file.txt', 'rb'); 

Newline modifier for Windows

Another special modifier exists that might come in handy for Windows users: t. If this is appended to the file mode, all \n line breaks are converted into \r\n as Windows applications might expect.


Working with Files in PHP: