Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 147 ยท Working with Files

Reading and Writing Files

Read and write files in PHP - file_get_contents, file_put_contents, file(), fopen modes, fgets and fwrite, appending, locking with LOCK_EX, error handling and __DIR__ paths.

Files are the simplest way for a program to remember things between runs: configuration, logs, exports, caches, uploaded documents. PHP was built for the web, but it has always been very good at files too, and the same functions work whether your script runs on a web server or on the command line.

PHP gives you two levels of tools. The whole-file functions file_get_contents(), file_put_contents() and file() read or write an entire file in one call, and they're what you'll use most of the time. The handle-based functions fopen(), fgets(), fwrite() and fclose() work piece by piece, which you need for big files, for appending line by line, and for fine control over locking and position. This lesson covers both, plus the parts that cause real bugs: file modes, paths, locking and error handling.

Every example below really creates and reads files on our server. Each run gets a fresh, empty folder, so the files exist only while that one run lasts. The next lesson, Files and Directories, covers listing, moving and deleting files.

Reading and writing a whole file

file_put_contents($path, $data) creates the file if needed, replaces its contents, and returns the number of bytes written. file_get_contents($path) returns the whole file as a string:

PHP Writing and reading a whole file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The first write reports Wrote 29 bytes (every character is one byte here, including the two \n newlines). The second file_put_contents() call replaces the file, so the final read shows only Replaced..

That replace-by-default behavior is the most important thing to remember. To add to the end instead, pass the FILE_APPEND flag:

PHP
file_put_contents($logPath, "User 42 logged in\n", FILE_APPEND);

file_put_contents() also accepts an array, whose elements are joined with no separator, and with LOCK_EX it locks the file while writing (more on locks below). Flags combine with |:

PHP
file_put_contents($logPath, $line, FILE_APPEND | LOCK_EX);

Reading a file as lines with file()

file($path) reads a file into an array with one element per line. By default each element keeps its newline, which surprises everyone once. Two flags fix that:

  • FILE_IGNORE_NEW_LINES removes the trailing newline from each element;
  • FILE_SKIP_EMPTY_LINES drops empty lines (it only works together with FILE_IGNORE_NEW_LINES).
PHP file() with and without flags

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

With the defaults, the first element is a 5-byte string, milk plus its newline (that's why the closing quote of the var_dump() output lands on the next line), and the array has 4 lines because the empty line counts. With both flags you get exactly milk, bread and eggs, numbered 0 to 2.

Working with file handles

The whole-file functions load everything into memory at once. A 2 GB log file won't fit in the default 128 MB memory limit, and even smaller files waste memory when you only need one line at a time. For those cases, open a handle with fopen() and read or write in pieces:

PHP Writing and reading line by line

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Step by step:

  • fopen($path, 'w') opens the file for writing (creating or emptying it) and returns a stream resource, the handle.
  • fwrite($handle, $string) writes at the current position and returns the number of bytes written (or false).
  • fclose($handle) flushes buffered data and releases the file. PHP closes handles automatically when the script ends, but closing them yourself matters in long-running scripts and before you read back what you wrote.
  • fgets($handle) returns the next line including its newline, or false at the end of the file. That's why the loop compares with !== false and the output uses rtrim().

Don't write while (!feof($in)) { $line = fgets($in); ... }. feof() only becomes true after a read has hit the end, so the loop runs one extra time with $line === false. Testing the return value of fgets() directly, as above, is always correct.

Other handle functions you'll meet: fread($h, $length) reads a number of bytes (for binary data), fputs() is an alias of fwrite(), fprintf($h, $format, ...) writes formatted text, ftell($h) returns the current position, fseek($h, $offset) moves it, and rewind($h) jumps back to the start.

File modes

The second argument of fopen() says what you're going to do. Choosing the wrong one can silently delete a file, so it's worth knowing all of them:

Mode Read Write If the file exists If it doesn't Starts at
r yes no opens it fails start
r+ yes yes opens it fails start
w no yes empties it creates it start
w+ yes yes empties it creates it start
a no yes opens it creates it end (every write appends)
a+ yes yes opens it creates it reads from start, writes append
x no yes fails creates it start
x+ yes yes fails creates it start
c no yes opens it, keeps contents creates it start
c+ yes yes opens it, keeps contents creates it start

Some practical rules:

  • a is the mode for logs: every fwrite() goes to the end, even if another process wrote in the meantime.
  • x ("exclusive create") is the safe way to create a file that must not already exist, like a lock file or a new report that must never overwrite an old one.
  • c opens for writing without emptying, so you can take a lock first and truncate afterwards with ftruncate().
  • Add b (rb, wb) for binary-safe mode. On Linux and macOS it changes nothing; on Windows it prevents newline translation, so it's a good habit for non-text files.
PHP Append mode and exclusive create

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Each fopen($log, 'a') adds a line instead of replacing the file, so all three events appear. (The time is date('H:i:s', 0), midnight on January 1, 1970, just to keep the output identical on every run.) The second fopen(..., 'x') fails because the report exists, which is exactly the protection you want. The @ hides the warning here because the code checks for false right away; the next section shows a cleaner way.

Handling errors

When a file operation fails, PHP's file functions do two things: they emit a warning (such as Failed to open stream: No such file or directory) and return false. Ignoring the false is a common source of confusing bugs later, so always check the result:

PHP
$contents = file_get_contents($path);
if ($contents === false) {
    throw new RuntimeException("Could not read $path");
}

Use === for that check: an empty file returns '', which is falsy but perfectly valid.

Checking is_file() or is_readable() first helps give a better message, but it can't replace checking the result: the file can disappear between the check and the read. A clean, reusable approach is to turn the warning into an exception for the duration of the call, as described in Custom Exceptions:

PHP Reading files without silent failures

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The existing file prints settings.ini: theme = dark. For the missing one, the warning becomes an exception with PHP's own detailed message, Error: file_get_contents(missing.ini): Failed to open stream: No such file or directory. (On a real server the message contains the full path; our editor shortens it.) The finally block restores the previous error handler whatever happens.

Paths and DIR

A relative path like data/prices.json is resolved against the current working directory, which is wherever the process was started, not the folder of the script. On the command line that's the folder you ran php from; under a web server it's usually the folder of the entry script, but that depends on the setup. So a relative path can work in one place and fail in another.

The fix is to build paths from __DIR__, the magic constant that holds the folder of the current file:

PHP
// fragile: depends on where the script was started
$prices = file_get_contents('data/prices.json');

// robust: always relative to this file
$prices = file_get_contents(__DIR__ . '/data/prices.json');

// one level up, e.g. from src/ to the project root
$config = file_get_contents(__DIR__ . '/../config/app.ini');

Use forward slashes /. They work on Windows too, so you rarely need the DIRECTORY_SEPARATOR constant. realpath() turns a path with .. into a clean absolute path and returns false if it doesn't exist; Files and Directories shows it in use.

Never build a path straight from user input, like file_get_contents(__DIR__ . '/pages/' . $_GET['page']). A visitor can send ../../../etc/passwd and read any file the server can. This is called path traversal; Secure Coding shows how to prevent it with a whitelist or basename() and realpath() checks.

Locking files

On a web server, many requests run at the same time. If two of them write to the same file at once, lines can get mixed up or lost. File locks make the processes take turns. flock($handle, LOCK_EX) takes an exclusive lock (for writing) and waits until no one else holds one; LOCK_SH takes a shared lock (for reading, many readers at once); LOCK_UN releases it.

Here's a visit counter, the classic case. Reading, incrementing and writing must happen under one lock, or two requests can both read 41 and both write 42:

PHP A counter protected by a lock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The mode c+ is the key detail: w+ would empty the file before the lock is taken, when another process might still be reading it. With c+ you lock first, then truncate. The output counts 1, 2, 3 and the file ends up containing 3.

For simple appends, file_put_contents($path, $line, FILE_APPEND | LOCK_EX) does the locking for you. Keep in mind that PHP locks are advisory: they only work if every program that touches the file also uses flock(). For data that many requests change at once, a database with transactions is the better tool.

Writing a file safely (atomic replace)

If a script crashes halfway through writing a config file, the file is left half-written. The standard defense is to write to a temporary file in the same folder and then rename() it over the original. On Linux and macOS a rename within one file system is atomic: readers see either the old file or the new one, never a mix.

PHP
$tmp = $path . '.tmp';
file_put_contents($tmp, $newContents, LOCK_EX);
rename($tmp, $path);

Choosing the right function

Task Use
Read a small or medium file completely file_get_contents()
Write or replace a file file_put_contents()
Append a line to a log file_put_contents($p, $line, FILE_APPEND | LOCK_EX)
Read lines of a small file into an array file($p, FILE_IGNORE_NEW_LINES)
Process a large file line by line fopen() + fgets() loop, or a generator
Read-modify-write under concurrency fopen($p, 'c+') + flock()
Create a file only if it doesn't exist fopen($p, 'x')
CSV data fgetcsv() / fputcsv() (CSV Files)
JSON data json_decode(file_get_contents($p), true) (JSON)

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. notes.txt contains "a". What does it contain after file_put_contents("notes.txt", "b");?

    Without FILE_APPEND, file_put_contents replaces the whole file. FILE_APPEND would give "ab".
  2. 2. Which fopen mode fails if the file already exists?

    x is exclusive create. w empties an existing file, a appends to it, and c opens it without emptying.
  3. 3. A file contains "one\ntwo\n". What is file($path)[0]?

    file() keeps each line's newline by default. Pass FILE_IGNORE_NEW_LINES to get "one".
  4. 4. What's wrong with while (!feof($h)) { echo strtoupper(fgets($h)); }?

    The loop runs once more than there are lines. Test the result instead with while (($line = fgets($h)) !== false).
  5. 5. A script in /app/src runs file_get_contents('data.txt') and is started from /home/kim. Where does PHP look?

    Relative paths are resolved against the current working directory, not the script's folder. Use DIR . '/data.txt' to get /app/src/data.txt.

Summary

  • file_get_contents() reads a whole file; file_put_contents() writes one and replaces it unless you pass FILE_APPEND. Add LOCK_EX to lock while writing.
  • file() returns an array of lines that keep their newlines; use FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES for clean lines.
  • For large files or fine control, use handles: fopen(), fgets() in a while (($line = fgets($h)) !== false) loop, fwrite(), fclose(). Don't loop on feof().
  • Modes: r read, w write and empty, a append, x create only if missing, c write without emptying; + adds the other direction, b is binary-safe.
  • File functions return false and emit a warning on failure. Check with === false, or turn the warning into an exception with a temporary error handler.
  • Build paths with __DIR__; relative paths depend on the working directory. Never put user input into a path unchecked.
  • flock() with LOCK_EX/LOCK_SH makes concurrent processes take turns (use c+ for read-modify-write); write to a temp file and rename() it for atomic replacement.

Next: Files and Directories