W3docs

PHP File Open: A Guide to Reading and Writing Files in PHP

PHP is a powerful and versatile scripting language that can be used to accomplish a wide range of tasks, including working with files. In this article, we will

Reading and writing files is one of the most common tasks in server-side programming: you save uploaded documents, generate logs, cache data, and read configuration files. PHP gives you a small, stable set of functions for this, and they all start with one call — fopen(). This chapter explains how to open a file, read from it, write to it, append to it, close it, and handle the errors you will inevitably hit along the way.

Understanding the fopen() Function

The fopen() function opens a file (or a URL) and returns a file handle — a resource you pass to every other file function. It takes two required arguments: the path to the file and the mode that decides what you are allowed to do with it and where the internal file pointer (the cursor that marks your position) starts.

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

If the file cannot be opened, fopen() returns false and emits a warning, so you should always check the return value before using the handle.

File modes

The mode is the single most important argument: it controls whether the file is read, overwritten, or appended to, and whether a missing file is created.

ModeReadWritePointer starts atTruncates?Creates if missing?
ryesnobeginningnono (fails)
r+yesyesbeginningnono (fails)
wnoyesbeginningyesyes
w+yesyesbeginningyesyes
anoyesendnoyes
a+yesyesendnoyes
xnoyesbeginningn/ayes (fails if exists)
x+yesyesbeginningn/ayes (fails if exists)

A few rules worth remembering:

  • Use r when the file must already exist and you only need to read it.
  • w and w+ erase the file's contents the moment it is opened — never use them when you want to keep existing data.
  • a and a+ are the safe choice for logs: they always write to the end and never truncate.
  • x and x+ protect against accidentally overwriting an existing file, which is useful for "create once" operations.

Note: On Windows, append b to the mode (e.g., rb, wb, ab) to open the file in binary mode and prevent newline translation that can corrupt non-text files. On Linux and macOS the b flag is harmless, so adding it everywhere keeps your code portable.

Reading Files in PHP

To read a file, open it in read mode (r) and use fread(). fread() takes the file handle and the number of bytes to read; pairing it with filesize() reads the whole file at once.

Here is an example that reads the entire contents of a file:

<?php
$file = fopen("example.txt", "r");
if ($file) {
    $contents = fread($file, filesize("example.txt"));
    fclose($file);
    echo $contents;
}
?>

Reading a file line by line

For large files, reading everything into memory is wasteful. Use fgets() to read one line at a time and feof() ("end of file") to stop when you reach the end:

<?php
$file = fopen("example.txt", "r");
if ($file) {
    while (!feof($file)) {
        $line = fgets($file);
        echo $line;
    }
    fclose($file);
}
?>

The shorter alternative: file_get_contents()

For straightforward reads where you just want the whole file as a string, file_get_contents() does the open, read, and close in a single call:

<?php
$contents = file_get_contents("example.txt");
echo $contents;
?>

Use fopen() + fread()/fgets() when you need fine-grained control (streaming, partial reads, locking); reach for file_get_contents() when you simply want the file's text.

Writing Files in PHP

To write to a file, open it in write mode (w) and use fwrite(). fwrite() takes the file handle and the string to write, and returns the number of bytes written (or false on failure). Remember that w truncates the file first, so it always starts from an empty file.

Here is an example that writes data to a file:

<?php
$file = fopen("example.txt", "w");
if ($file) {
    fwrite($file, "This is some data.");
    fclose($file);
}
?>

Just like reading, there is a one-call shortcut for writing: file_put_contents() opens, writes, and closes the file in a single statement.

Appending Data to Files in PHP

To append data to a file in PHP, you can use the fopen() function in append mode (a) and the fwrite() function. This allows you to add data to the end of a file, rather than overwriting it.

Here is an example that appends data to a file:

<?php
$file = fopen("example.txt", "a");
if ($file) {
    fwrite($file, "This is some additional data.");
    fclose($file);
}
?>

Closing Files in PHP

It is important to close a file after you have finished working with it, to free up system resources and prevent data corruption. This can be done using the fclose() function, which takes the file pointer returned by fopen() as its argument.

Here is an example that demonstrates the proper way to close a file in PHP:

<?php
$file = fopen("example.txt", "r");
if ($file) {
    // Perform file operations here
    fclose($file);
    echo "File closed successfully.";
}
?>

Error Handling in PHP

It is important to handle errors properly when working with files in PHP. For example, if you try to open a file that does not exist, or if you try to write to a file that is not writable, you will receive an error.

To handle errors, you can use the if statement and the $file variable returned by fopen(). If fopen() returns false, it means that an error has occurred. In production environments, you may use the @ error suppression operator or configure a custom error handler to manage warnings gracefully without breaking the page layout.

Here is an example that demonstrates error handling in PHP:

<?php
$file = fopen("example.txt", "r");
if ($file) {
    $contents = fread($file, filesize("example.txt"));
    fclose($file);
    echo $contents;
} else {
    echo "Error: Unable to open file.";
}
?>

Summary

fopen() is the foundation of file handling in PHP. The mode you choose decides everything: r reads, w overwrites, a appends, and x creates a file only if it does not already exist. Read with fread()/fgets(), write with fwrite(), always check whether the handle is valid, and close it with fclose() when you are done. For simple one-shot reads and writes, prefer file_get_contents() and file_put_contents().

To go deeper, see fopen(), fread(), and fwrite(), and the broader PHP File Handling and PHP Filesystem chapters.

Practice

Practice
Which functions in PHP are used to open or read a file?
Which functions in PHP are used to open or read a file?
Was this page helpful?