php
  1. php-open-file

PHP Open File

Syntax

$file = fopen($filename, $mode);

Example

<?php
$filename = "example.txt";
$mode = "r";
$file = fopen($filename, $mode);
if($file === false)
{
    echo "Error: Couldn't open file.";
}
else
{
    echo "File opened successfully.";
    fclose($file);
}    
?>

Output

If the file is opened successfully, the output will be:

File opened successfully.

If the file cannot be opened, the output will be:

Error: Couldn't open file.

Explanation

The fopen() function in PHP is used to open a file. In the example above, we are opening example.txt in read mode ($mode = "r";). The fopen() function returns a file pointer resource if the file is opened successfully, and returns false if the file cannot be opened.

The fclose() function is used to close an opened file pointer resource to free up system resources.

Use

Opening a file is a common operation when working with files in PHP. You can open a file for reading, writing or appending by specifying the appropriate $mode parameter.

Important Points

  • Always check the return value of fopen() to ensure the file was opened successfully.
  • Always close the file pointer resource with fclose() to free up system resources.

Summary

The fopen() function in PHP is used to open a file for reading, writing or appending. Always check the return value of fopen() to ensure the file was opened successfully, and always close the file with fclose() to free up system resources.

Published on: