Write syntax to open a file in PHP?

PHP fopen() function is used to open file or URL and returns resource. It accepts two arguments: $filename and $mode.

Syntax:

resource fopen ( string $filename , string $mode [, bool $use_include_path = false [, resource $context ]] )

To open a file in PHP, you typically use the fopen() function. Here’s the syntax:

php
$file_handle = fopen("filename", "mode");

Where:

  • "filename" is the name of the file you want to open.
  • "mode" specifies the mode in which you want to open the file. This can be "r" for reading, "w" for writing (and truncating the file to zero length), "a" for appending, "r+" for reading and writing, "w+" for reading and writing (and truncating the file to zero length), etc.

For example, to open a file named “example.txt” for reading:

php
$file_handle = fopen("example.txt", "r");

Make sure to handle errors properly, for instance, checking if the file exists before attempting to open it, and handling errors that might occur during the file opening process.