PHP fopen() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
Filesystem

Definition

In PHP, fopen() opens a file or a URL and gives you a handle that other functions, such as fgets(), fwrite() and fclose(), can use.

The mode you pass decides what you can do with the file, such as read only, write, or append. After you are done, close the handle with fclose().

Syntax

Call fopen() with the values you need. Start with this line.

PHP
$handle = fopen('notes.txt', 'r');
CallWhat it does
fopen('notes.txt', 'r')Opens an existing file for reading only, starting at the beginning.
fopen('notes.txt', 'w')Opens the file for writing and clears its content. The file is created if needed.
fopen('log.txt', 'a')Opens the file for writing and adds new text to the end.

Common modes are r (read), w (write and clear), a (append), x (create, fail if it exists) and c (write without clearing). Add a plus sign, as in r+, to allow both reading and writing. On Windows, add b, as in rb, for binary files such as images.

Library declarations
PHP
fopen(string $filename, string $mode, bool $use_include_path = false, ?resource $context = null): resource|false

Parameters

ParameterDescription
filenameRequired. The path of the file or a URL such as php://memory.
modeRequired. A short text that sets how the file is opened, for example r, w, a, x or c.
use_include_pathOptional. Set to true to search for the file in the include_path as well. The default is false.
contextOptional. A stream context created with stream_context_create(). The default is null.

Return Value

Return ValueDescription
resourceReturns a file handle on success. In PHP 8 this is a resource that you pass to other file functions.
falseReturns false on failure, for example when the file is missing in r mode or the folder is not writable.

PHP Examples

Example 1 — Write and Read a File

Open a file to write a line, close it, and open it again to read the line back.

PHP
<?php
$file = __DIR__ . '/fopen_demo.txt';

$fp = fopen($file, 'w');
fwrite($fp, 'Hello from fopen!');
fclose($fp);

$fp = fopen($file, 'r');
echo fgets($fp), PHP_EOL;
fclose($fp);

unlink($file);

How It Works

  1. fopen() in w mode creates the file and fwrite() puts the text inside it.
  2. fclose() closes the handle so the data is saved.
  3. fopen() in r mode opens the same file for reading.
  4. fgets() reads the first line, which is printed, and the handle is closed again.

Example 2 — Open a File That Is Missing

In r mode, fopen() returns false when the file does not exist. Always test the handle.

PHP
<?php
$fp = @fopen(__DIR__ . '/missing.txt', 'r');

if ($fp === false) {
    echo "Could not open the file", PHP_EOL;
} else {
    echo fgets($fp);
    fclose($fp);
}

How It Works

  1. The r mode never creates a file, so a missing file cannot be opened.
  2. fopen() returns false and the @ sign hides the PHP warning.
  3. The if check stops the script before fgets() receives an invalid handle.
  4. A friendly message is shown, and no fclose() is needed because nothing was opened.

Example 3 — Append Lines to a Log

The a mode adds new text at the end of the file without erasing what is already there.

PHP
<?php
$file = __DIR__ . '/log.txt';

foreach (['Started', 'Working', 'Done'] as $line) {
    $fp = fopen($file, 'a');
    fwrite($fp, $line . PHP_EOL);
    fclose($fp);
}

$fp = fopen($file, 'r');
while (!feof($fp)) {
    $line = fgets($fp);
    if ($line !== false) {
        echo trim($line), PHP_EOL;
    }
}
fclose($fp);

unlink($file);

How It Works

  1. Each pass of the loop opens the file in a mode that adds to the end.
  2. fwrite() adds one line, and fclose() saves it.
  3. The file is then opened for reading, and feof() tells the loop when the end is reached.
  4. fgets() returns false at the end, so the check avoids printing an empty line.

Frequently Asked Questions

It opens a file or URL and returns a handle. You use the handle with functions like fgets(), fwrite() and fclose().
r reads an existing file, w writes and erases the old content first, and a writes at the end and keeps the old content.
Usually the file does not exist in r mode, the folder is not writable, or the path is wrong. Check the path and the folder permissions.
Yes, it is a good habit. PHP closes open files at the end of the script, but closing early frees resources and makes sure the data is saved.
Use file_get_contents() when you only need to read the whole file at once. Use fopen() when you want to read or write step by step, or lock the file.

Next: fpassthru()

fpassthru() reads everything left in an open file and sends it straight to the output.

fpassthru() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful