Skip to content

PHP Tutorial File Handling

Opening and Closing Files

Lesson 164 of 369 2 min read By Deepak Paswan Updated Oct 5, 2026

To work with a file line by line, you open it, use it and close it. The three steps use fopen(), a read or write function, and fclose().

index.php
PHP
<?php
$handle = fopen("notes.txt", "w");   // open for writing
fwrite($handle, "Hello file\n");
fclose($handle);                     // always close

echo file_get_contents("notes.txt");
Output
OUTPUT
Hello file

fopen() returns a file handle (a resource, see Resources). You give that handle to the other file functions.

File modes

The second argument says what you want to do.

ModeMeaningIf the file does not exist
rRead only, start at the beginningError
r+Read and writeError
wWrite only, empties the file firstCreated
w+Read and write, empties the fileCreated
aAppend: write at the endCreated
a+Read and appendCreated
xCreate and write, fails if the file existsCreated
cWrite without emptyingCreated

Add b (as in rb or wb) for binary files. It makes no difference on Linux, but on Windows it prevents line-ending conversion.

Check that opening worked

fopen() returns false and a warning when it fails: file missing, no permission or wrong path.

index.php
PHP
<?php
$handle = @fopen("does-not-exist.txt", "r");

if ($handle === false) {
    echo "Could not open the file.";
} else {
    fclose($handle);
}
Output
OUTPUT
Could not open the file.

The @ hides PHP’s warning here to keep the output short. In real code, avoid @, and handle the failure instead (for example log it and show a friendly message).

Why close the file

PHP closes open files when the script ends, but closing as soon as you are done:

  • Frees the file for other processes.
  • Makes sure buffered data is written.
  • Keeps you from running out of open file handles in long scripts.

Safe pattern

index.php
PHP
<?php
$handle = fopen("log.txt", "a");

if ($handle === false) {
    throw new RuntimeException("Cannot open log.txt");
}

try {
    fwrite($handle, "Started\n");
} finally {
    fclose($handle);   // runs even if something above fails
}

echo "Done";
Output
OUTPUT
Done

finally guarantees fclose() runs. You will meet it in Error Handling.

When you do not need fopen

For small files, file_get_contents() and file_put_contents() are shorter. See file_get_contents() and file_put_contents(). Use fopen() when the file is large, or you need to read or write it in pieces.

lightbulb
Windows paths
Write paths with forward slashes (C:/data/file.txt). PHP understands them on Windows, and you avoid escaping backslashes.