fopen()

Last updated on

PHP has great tools to handle external files such as opening, writing, deleting and more else, in this tutorial we will focus more in “fopen” function.

Let’s see how the ‘fopen’ function works in PHP and see some practical examples.

The PHP fopen Syntax

PHP fopen function is a built-in callback function designed to manipulate and access the external files in PHP.

Once you provide the pathway to the file system, it allows you to open files for reading, writing, or appending data to the file according to it modes argument.

Moreover, the “fopen” function has two required parameters:

  • The file name or path.
  • The basic mode of the opened file.

In the following part, you will see all modes used inside this function with an explanation. Let’s first understand its syntax.

fopen( filename, filemode, use_include_path, context )

The following list shows you the arguments of the fopen function:

  • filename: This parameter is required; it contains the name of the file, including the full path of the URL, which should be a correct file path.
  • filemode: This is a string parameter that defines the mode type, determining which mode this file should open.
  • use_include_path: This is an optional parameter. If you set it to TRUE, the function will also search for the file in the include_path.
  • context: This is also an optional parameter; we can use it to specify a context for the file stream.

You have just understood the syntax and its parameters, but you haven’t learned about the modes of the ‘fopen’ function. In the following section, I will explain it in-depth.

PHP fopen Modes

As I mentioned before, the mode in the “fopen” function is a string parameter that defines the mode in which the file can be opened. In the following list, you will see a brief explanation for each one:

  • Read only ( r ): This mode opens the file for reading only, and placing the pointer at the beginning of the file.
  • Write only ( w ): Here, it opens the file for writing only and creates the file if the requested file path doesn’t exist. However, if the file already exists, it will truncate it to zero length.
  • Append ( a ): This opens the file for writing. It detects if the file doesn’t exist, then creates it, but it positions the pointer at the end of the file, which means the data will be overwritten.
  • Exclusive creation ( x ): This creates and opens a file exclusively for writing mode which means if the file already exists the “fopen” process will fail and creates an error.
  • Open for writing only ( c ): Here, the pointer is placed at the beginning of the file. But if it doesn’t exist, it will create the file. However, if the file already exists, it will not truncate the file.
  • Read/Write ( r+ ): The “r+” mode opens the file for both reading and writing, also placing the pointer at the beginning of the file.
  • Read/Write ( w+ ): This mode opens the file for both operations: reading and writing. It detects if the file doesn’t exist, then creates it. However, if it finds the file in the path, it will truncate it to zero length.
  • Read/Append ( a+ ): Here, this mode will open the file for reading and writing. It detects if the file doesn’t exist, then creates it and places the pointer at the end of the file. It will not truncate the data inside the file.
  • Read/Write ( x+ ): This creates the file if it doesn’t exist for reading and writing. However, if the file is already found, the operation will fail and creates an error.
  • Read/Write ( c+ ): The ‘c+’ mode opens the file for reading and writing. If the file exists, it will not truncate the data inside but will place the pointer at the beginning. However, It detects the file’s existence; if it is not present, it will create the file in the requested path.

To summarize modes in the ‘fopen’ PHP callback function, check to the below table:

FOpen Models in PHP

Let’s see a quick example for the “read only” mode:

<?php $fopen= fopen("codedtag.txt", "r"); ?>

Anyway, let’s move into to below section to see more examples.

PHP fopen() Examples

In the following example, I will use the fclose callback to close the file stream, and this will occur once the fopen has completed its operation.

<?php

$my_file = "codedtag.txt";
$mode = "r";
$fopen = fopen($my_file, $mode);

if ($fopen) {
    echo "File opened successfully!";
    // Perform file operations here

    fclose($fopen); // Close the file when done
} else {
    echo "Error opening the file.";
}

?>

According to this example, I used the fopen function to open the file “codedtag.txt” using the “read-only” mode.

If the file is successfully opened, it will display the success message.

Once it completes its operation, the fclose callback will close the file stream.

Note: When calling the fopen function, you should use the fclose callback after completing your tasks on the file to end the file access.

But, if the file doesn’t exist, the program will produce a warning message like the below one:

Warning: fopen(codedtag.txt): Failed to open stream: No such file or directory in C:\xampp\htdocs\php\fopen.php on line 5
Error opening the file.

So, to prevent this warning, we need to use another PHP built-in function, which is file_exists, to check whether the ‘codedtag.txt’ file already exists or not. This can be achieved with an additional if statement in the code.

<?php

$my_file= "codedtag.txt";
$mode = "r";

if( file_exists( $my_file) ) {
  
  $fopen= fopen($my_file, $mode);
  
  if ($fopen) {
      echo "File opened successfully!";
      // Perform file operations here
  
      fclose($fopen); // Close the file when done
  } else {
      echo "Error opening the file.";
  }

}

?>

Actually, there is another mode can create the file if it doesn’t exists which is the “a+” flag, here is an example:

<?php fopen("codedtag.txt", "a+"); ?>

By executing this example with the “a+” mode, the file will be created if it doesn’t exist, and it will not overwrite the existing file.

Let’s summarize it.

Wrapping Up

Through this exploration, we have explained various modes using the fopen function in PHP and understood how they work for reading, writing, and appending data to files. Let’s summarize it in a few points:

  • The “fopen” function is designed to access external files in PHP.
  • You should use “fclose” when using "fopen" to end file access.
  • When using the "fopen" function in PHP, you need to check whether the file already exists or not in some mode cases to avoid any errors.

Thank you for reading. Happy Coding!

Frequently Asked Questions (FAQs)

  • What is PHP fopen and why is it used?

    fopen in PHP is a function used to open a file with specific modes like read, write, or append. It helps access external files for operations like reading data, writing new data, or appending existing data.
  • What are the required parameters for fopen?

    fopen requires two main parameters:
    - filename: The file path or name.
    - filemode: The mode, such as "r" for read or "w" for write, which determines how the file is accessed.
  • What are fopen modes in PHP?

    Modes in fopen define how a file is accessed:
    - "r": Read-only.
    - "w": Write-only, truncates file or creates a new one.
    - "a": Append-only, writes to the end of the file.
    - "x": Exclusive write, fails if the file exists.
    - "c": Write-only, doesn’t truncate existing data.
    - "r+": Read and write.
    - "w+": Read and write, truncates file if it exists.
    - "a+": Read and write, appends to the end of the file without truncating.
  • How do you close a file opened with fopen?

    Use fclose to close a file opened with fopen to free up resources.
    Example:
    $file = fopen("file.txt", "r");
    $file = fopen("file.txt", "r");
    fclose($file); 
  • How can I avoid errors if the file doesn’t exist?

    Use file_exists to check if a file exists before opening it with fopen.
    Example:
    if (file_exists("file.txt")) {
    $file = fopen("file.txt", "r");
    fclose($file);
    } else {
    echo "File does not exist.";
    } 
  • What happens if you open a file in write mode and it already exists?

    When using "w" mode, fopen will truncate the file to zero length, essentially clearing its contents. If you want to append data without removing existing content, use "a" mode.
  • How do I create a file if it doesn’t exist?

    To create a file if it doesn’t exist, use modes like "a" or "a+".
    Example:
    fopen("newfile.txt", "a+"); 
  • Can I read and write to the same file with fopen?

    Yes, modes like "r+", "w+", and "a+" allow both reading and writing to a file. "r+" starts from the beginning, "w+" truncates, and "a+" appends.
  • How do I read data from a file opened with fopen?

    Use functions like fread, fgets, or fgetcsv to read data from a file after opening it with fopen in read mode ("r" or "r+").
    Example:
    $file = fopen("file.txt", "r");
    $content = fread($file, filesize("file.txt"));
    echo $content;
    fclose($file); 
  • What does fopen return?

    fopen returns a file handle (resource) on success, which is used to perform file operations. If it fails, it returns false.
Share on: