W3docs

fopen()

The fopen() function is a built-in PHP function that is used to open a file. This function returns a file pointer that can be used to read from or write to the

What is the fopen() Function?

The fopen() function is a built-in PHP function that opens a file (or a URL) and returns a file pointer — a resource handle you then pass to functions like fread(), fwrite(), fgets(), and fclose() to actually read, write, and close the stream. On failure it returns false and emits an E_WARNING.

Almost every file operation in PHP that reads or writes incrementally starts with fopen(). (For one-shot reads and writes you usually reach for file_get_contents() and file_put_contents() instead — see When not to use fopen().)

Syntax

fopen(string $filename, string $mode, bool $use_include_path = false, $context = null): resource|false
ParameterDescription
$filenamePath to the file, or a URL (e.g. https://…, php://stdin) when wrappers are enabled.
$modeHow to open the file — read, write, append, etc. See the table below.
$use_include_pathIf true, PHP also searches the include_path for the file.
$contextAn optional stream context created with stream_context_create().

It returns a file-pointer resource on success, or false on failure.

fopen() modes

The $mode argument is the part people get wrong most often. It controls whether the file is read, written, or both, where the internal pointer starts, and whether the file is truncated or must already exist.

ModeReadWritePointer starts atTruncates?If file is missing
ryesnobeginningnowarning, returns false
r+yesyesbeginningnowarning, returns false
wnoyesbeginningyescreates it
w+yesyesbeginningyescreates it
anoyesendnocreates it
a+yesyesend (writes always append)nocreates it
xnoyesbeginningnocreates it; fails if it exists
x+yesyesbeginningnocreates it; fails if it exists

You can append b (binary, e.g. 'rb') or t (text) to any mode. Always use 'b' for non-text files such as images or executables — on Windows the text mode silently translates line endings and corrupts binary data. On Unix the two are identical, so 'b' is the safe default everywhere.

Basic example: reading a file

Open a file in read mode, read its contents, then close it. Always check the return value before using the handle, and always fclose() when you're done so the operating system can release the descriptor.

<?php

$filename = 'myfile.txt';
$file = fopen($filename, 'r');

if ($file === false) {
    echo "Unable to open file!";
} else {
    echo fread($file, filesize($filename));
    fclose($file);
}

We open myfile.txt in read-only mode and check the handle with a strict === false comparison — that matters because a valid resource is truthy, but so are some non-error values, so loose checks can bite you later.

Writing to a file

Opening with 'w' creates the file if it doesn't exist and truncates it to zero length if it does. Use 'a' instead when you want to add to the end without erasing what's already there (handy for log files).

<?php

$file = fopen('log.txt', 'w');     // create / overwrite
fwrite($file, "First line\n");
fwrite($file, "Second line\n");
fclose($file);

$file = fopen('log.txt', 'a');     // append, keep existing content
fwrite($file, "Appended later\n");
fclose($file);

echo file_get_contents('log.txt');

This prints all three lines because 'a' added to the file rather than replacing it. See fwrite() for the writing side and feof() for detecting end-of-file while looping.

Reading line by line

For large files, don't read everything into memory at once. Pair fopen() with fgets() and feof() to stream one line at a time:

<?php

$file = fopen('myfile.txt', 'r');
if ($file) {
    while (!feof($file)) {
        $line = fgets($file);
        if ($line !== false) {
            echo $line;
        }
    }
    fclose($file);
}

Common gotchas

  • Forgetting to check false. If the path is wrong or permissions deny access, fopen() returns false and warns. Calling fread() on false throws a TypeError in PHP 8+.
  • Not closing the handle. Open descriptors are a limited resource; leaking them in a long-running process eventually exhausts the OS limit. Always fclose(), ideally in a finally block.
  • Wrong mode. Using 'w' when you meant 'r' silently wipes the file. Reach for 'x' when you specifically want creation to fail if the file already exists.
  • Relative paths. They resolve against the script's current working directory, which isn't always what you expect. Prefer absolute paths or __DIR__ . '/file.txt'.

When not to use fopen()

If you just need the whole file as a string, or to dump a string to a file in one call, skip the open/read/close dance:

GoalSimpler function
Read an entire file into a stringfile_get_contents()
Write a string to a file in one callfile_put_contents()
Read a file into an array of linesfile()
Stream a file straight to outputreadfile()

Reach for fopen() when you need fine-grained, incremental control — reading huge files in chunks, appending to a log, or working with non-file streams like php://stdin.

Conclusion

fopen() is the foundation of low-level file handling in PHP: it returns a file pointer that you read from with fread() / fgets(), write to with fwrite(), and always release with fclose(). Pick the right mode, check the return value, and close the handle, and the rest of PHP's file-handling functions follow naturally.

Practice

Practice
What does the PHP 'fopen' function do according to the mentioned URL?
What does the PHP 'fopen' function do according to the mentioned URL?
Was this page helpful?