CodeBlanks Logo Icon CodeBlanks

Opening files with fopen()

PHP course · Intermediate · Lesson 72/115

Learn to open a file in different modes (r, w, a) with fopen().

Opening files with fopen()

file_get_contents() reads the whole file at once; but sometimes you want to process a file step by step, in chunks. For that you first open it with fopen(), then read or write through the returned handle.

For example, $handle = fopen('data.txt', 'r'); opens data.txt in read mode and returns a handle. You then use this handle for later reads or writes.

If fopen() fails it returns false. It is a good habit to check the handle before using it.

Common file modes: r, w, a

fopen() takes three main modes:

  • 'r' — read mode. The cursor is at the start, the file cannot be modified.
  • 'w' — write mode. If the file does not exist it is created; if it exists it is truncated and the cursor is at the start.
  • 'a' — append mode. If the file does not exist it is created; if it exists the cursor is at the end and the existing content is preserved.

Picking the wrong mode can cause data loss. For example, opening a file with 'w' immediately erases its previous content. Choose the mode carefully.

Exercise Open the file in read mode

First use file_put_contents() to write 'content' into data.txt (given part). Then open the file with fopen() in 'r' mode and store the handle in $handle. If the handle is valid, print a short message with echo.

Show example solution
Write $handle = fopen(__DIR__ . '/data.txt', 'r'); then check with if ($handle) { echo 'File opened'; }.
Example solution:
<?php
// Create the test file
file_put_contents(__DIR__ . '/data.txt', 'content');

// Open the file in read mode
$handle = fopen(__DIR__ . '/data.txt', 'r');

// Print a message if it opened
if ($handle) {
    echo 'File opened';
}

Test yourself

  1. Which mode opens a file for reading only?

    • 'w' mode
    • 'a' mode
    • 'r' mode
    • 'x' mode
    Show answer

    'r' mode — Correct. 'r' mode opens the file for reading only; no writing is allowed.

  2. Open the file in read mode

    $handle = fopen('data.txt', ____);
    Show answer
    $handle = fopen('data.txt', 'r');
  3. Match the file modes

    'r' mode
    Read only
    'w' mode
    Truncate and write
    'a' mode
    Append to the end
    fopen()
    Opens the file

All lessons in Intermediate