Reading, Writing and Permissions

2.Reading, Writing and Permissions

M

In this chapter

We'll learn how to read a whole file with file_get_contents() and file(), how to write and append with file_put_contents(), how to tell success from failure, what Unix file permissions like 0644 and 0755 mean and which user PHP runs as, and how to read a file's size, modification time and other metadata.

15–17 min

The Problem in Real Life

The booking page saves data/bookings.json with file_put_contents(). The reminder script reads it and, after sending each SMS, writes back "reminded": true. On the server, that write fails: "file_put_contents(/srv/bookbay/data/bookings.json): Failed to open stream: Permission denied".

The web server runs PHP as the user www-data, which created the file. Cron runs the reminder script as the user bookbay. Same file, two users, and only one of them may write.

M

On a server, every file has an owner and rules. PHP is just another user who has to follow them.

Marcus

Hoping a Write Worked vs. Knowing Who May Write What

Whole files at once

file_get_contents() and file_put_contents() read and write a file in one call.

Failure is false

Both return false and warn when something goes wrong. The code must check.

Owners and permissions

Read, write and execute rights for the owner, the group and everyone else.

Reading, Writing and Permissions

Getting data in and out of files: the simplest file functions read or write a whole file in one call. This chapter covers them, and the rules every server enforces:

  • Reading: file_get_contents() and file().
  • Writing and appending: file_put_contents() and its flags.
  • Checking for failure: false, warnings and exceptions.
  • Permissions: owners, groups and modes like 0644.
  • Metadata: size, modification time and more.

Reading: file_get_contents($path) returns the whole file as one string — perfect for a JSON file or a template. file($path) returns an array of lines instead; add FILE_IGNORE_NEW_LINES to drop the line endings and FILE_SKIP_EMPTY_LINES to skip blank lines. Both read everything into memory at once, which is fine for files of a few megabytes. For a 2 GB log file, read it piece by piece with a stream (chapter 4).

Reading a whole file, or its lines
<?php
$dir = '/tmp/bookbay';
@mkdir($dir, 0775, true);
file_put_contents("$dir/bookings.json", '[{"id":4811,"customer":"Tom Hart"}]');
file_put_contents("$dir/holidays.txt", "2026-12-25\n2026-12-26\n\n2027-01-01\n");
$bookings = json_decode(file_get_contents("$dir/bookings.json"), true, flags: JSON_THROW_ON_ERROR);
echo $bookings[0]['customer'], "\n";
$holidays = file("$dir/holidays.txt", FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
print_r($holidays);
// Tom Hart
// Array ( [0] => 2026-12-25 [1] => 2026-12-26 [2] => 2027-01-01 )

Writing and appending: file_put_contents($path, $data) creates the file if it doesn't exist, replaces its whole content if it does, and returns the number of bytes written. The flag FILE_APPEND adds to the end instead — the right choice for a log. LOCK_EX locks the file while writing, so two appends don't mix their lines (chapter 6 explains locks). If $data is an array, its values are joined together; for structured data, encode it first with json_encode().

Replacing and appending
<?php
$log = '/tmp/bookbay-reminders.log';
var_dump(file_put_contents($log, "reminder log\n")); // replaces: int(13)
var_dump(file_put_contents($log, "sent to Tom Hart\n", FILE_APPEND | LOCK_EX)); // appends: int(17)
var_dump(file_put_contents($log, "sent to Ann Lee\n", FILE_APPEND | LOCK_EX)); // int(16)
echo file_get_contents($log);
// reminder log
// sent to Tom Hart
// sent to Ann Lee

Checking for failure: these functions don't throw. On failure they raise a warning and return false (Act 14): a missing folder, no permission, a full disk. So compare with === false — never with !, because an empty file correctly returns "" and writing an empty string returns 0. Or install the error handler from Act 14 that turns warnings into ErrorException, and catch that. For writes, also compare the number of bytes with strlen($data): a full disk can write only part of the data.

Checking for failure properly
<?php
$json = '{"holidayPercent":10}';
$written = @file_put_contents('/tmp/no-such-folder/settings.json', $json); // @ only to keep the demo short
if ($written === false) {
echo "Could not save the settings\n";
} elseif ($written !== strlen($json)) {
echo "Only {$written} of ", strlen($json), " bytes were written\n";
}
file_put_contents('/tmp/empty.txt', '');
$content = file_get_contents('/tmp/empty.txt');
var_dump($content === false, !$content); // false, true: an empty file is NOT a failure
// Could not save the settings
// bool(false)
// bool(true)

Permissions: on Linux, every file and folder has an owner (a user), a group, and three sets of rights: for the owner, for the group, and for everyone else (others). Each set says whether that person may read (r = 4), write (w = 2) and execute (x = 1) — for a folder, "execute" means "may enter it". The three sums make a number written in octal with a leading 0: 0644 means the owner can read and write (4+2), the group and others can only read. chmod($path, 0640) changes them; fileperms() reads them. PHP runs as the web server's user (often www-data) for web requests, and as whoever started it on the command line — today's bug. The fix: put both users in one group that may write data/. The table below lists the common modes.

Table — Common permission modes
ModeOwnerGroupOthersTypical use
0644read, writereadreadCode and normal files
0640read, writeread—Files with private data (bookings, .env)
0664read, writeread, writereadData files shared by two users in one group
0755allread, enterread, enterNormal folders
0775allallread, enterFolders two users in one group write to
0777allallallNever: anyone can change anything

Reading the mode 0640

0640

octal: the leading 0 says "read as base 8"

three digits

6 = owner

read 4 + write 2

4 = group

read 4

0 = others

nothing

so

www-data (owner)

may read and change bookings.json

bookbay (in the group)

may read it

everyone else

may not even read it

The permission error, and the fix on the server
$ ls -l /srv/bookbay/data
-rw-r--r-- 1 www-data www-data 2318 Nov 6 09:12 bookings.json
$ php bin/send-reminders.php # runs as the user bookbay
PHP Warning: file_put_contents(/srv/bookbay/data/bookings.json): Failed to open stream: Permission denied
# fix: one shared group that may write data/, files 0664, folder 0775
$ sudo usermod -aG www-data bookbay
$ sudo chmod 0775 /srv/bookbay/data && sudo chmod 0664 /srv/bookbay/data/bookings.json

Who should be able to write what: the web server's user should be able to write only where it must — data/ and storage/ — and only read the code. If PHP can rewrite its own .php files, one security hole lets an attacker change the application itself. Never "fix" a permission error with chmod 0777 (everyone may do everything): it makes the problem invisible and the server unsafe. Windows has a different system (access-control lists), so chmod() there only switches the read-only flag; permissions matter mostly on the Linux server.

Metadata: filesize($path) returns the size in bytes, filemtime($path) the time of the last change as a Unix timestamp (format it with date()), and stat($path) returns everything at once, including the owner's id. touch($path) creates an empty file or updates its time. Like the checks in chapter 1, these results are cached within a request, so call clearstatcache() after changing a file. A common use: show "bookings last updated 2 minutes ago", or skip re-reading a file that hasn't changed.

Metadata and permissions from PHP
<?php
$file = '/tmp/bookbay/bookings.json';
@mkdir(dirname($file), 0775, true);
file_put_contents($file, '[{"id":4811,"customer":"Tom Hart"}]');
echo filesize($file), " bytes\n";
echo "changed ", date('Y-m-d', filemtime($file)), "\n";
printf("mode %o\n", fileperms($file) & 0777); // the last three octal digits
chmod($file, 0640);
clearstatcache(); // otherwise the cached 644 comes back
printf("mode %o\n", fileperms($file) & 0777);
// 35 bytes
// changed 2026-11-02
// mode 644
// mode 640

Key Takeaway

file_get_contents() reads a whole file as a string, file() as an array of lines (FILE_IGNORE_NEW_LINES); file_put_contents() creates or replaces a file, FILE_APPEND adds to it, LOCK_EX locks while writing. They don't throw: on failure they warn and return false, so compare with === false and check written bytes against strlen(). Linux permissions give read (4), write (2) and execute (1) to the owner, the group and others — 0644 for files, 0755 for folders, never 0777 — and PHP acts as the web server's user or the CLI user. Only data/ and storage/ should be writable. filesize(), filemtime() and stat() read metadata, cached until clearstatcache().

Why This Matters

Reading and writing files is everyday work: settings, exports, caches, logs. Doing it with proper failure checks is the difference between "the export is empty" and "the export failed: disk full".

Permission errors are among the most common deployment problems, and the most dangerously "fixed" ones. Knowing what 0644 means and which user PHP runs as lets you fix them properly instead of with 0777.

The data folder is shared by the right group, writes are checked, and the reminder log is appended line by line. Now Olivia wants a nightly backup of bookings.json in backups/2026/11/, old backups deleted after 30 days, and a list of every photo uploaded by the barbers. That needs folders — creating them, listing them and removing them. That's the next chapter: working with directories.