Files and Paths

1.Files and Paths

M

In this chapter

We'll learn how files and folders are organised on a server, the difference between absolute and relative paths and why relative ones break, how __DIR__ builds paths that always work, how to take a path apart with basename(), dirname() and pathinfo(), and how to check whether a file or folder exists before using it.

13–15 min

The Problem in Real Life

A week before launch, BookBay still has no database — that's Act 18. Until then, Marcus wants the bookings saved in a file, data/bookings.json, so nothing is lost when the server restarts. Mia writes file_put_contents('data/bookings.json', ...) in the booking page, and it works.

Then the reminder script, run by cron from the home folder, fails: "Failed to open stream: No such file or directory". The same path, data/bookings.json, means a different place depending on where PHP was started — exactly the Act 10 bug, now with data files.

M

I wrote one path. Why does it point to two different places?

Mia

Paths That Depend on Where You Are vs. Paths That Always Work

A tree of folders

Every file has one full address from the root of the disk.

Relative to what?

A relative path starts from the current working directory — which changes with how PHP was started.

Check before you use

is_file(), is_dir() and is_readable() answer before a warning does.

Files and Paths

Where files live: this Act saves bookings and photos to the server's disk. Before reading or writing anything, PHP needs to find the right file. This chapter covers:

  • Filesystem basics: files, folders and the tree they form.
  • Absolute and relative paths: and the current working directory.
  • Paths that always work: built from __DIR__.
  • Taking paths apart: basename(), dirname(), pathinfo() and realpath().
  • Checking files: file_exists(), is_file(), is_dir() and friends.

Filesystem basics: a disk is organised as a tree: folders (also called directories) contain files and other folders. On Linux servers the tree starts at the root, /, and BookBay's project lives at /srv/bookbay, with public/ for the web pages, src/ for code, data/ for the bookings file and storage/uploads/ for photos. On Windows each drive has its own root, like C:\. PHP accepts forward slashes / on every system, including Windows, so always write paths with /. The diagram below shows BookBay's tree.

BookBay on the server

/

the root

contains

/srv/bookbay

the project

contains

public/

book.php — the only folder the web can reach

src/

code

data/

bookings.json

storage/uploads/

barber photos

a path from __DIR__

From public/book.php:

__DIR__ . '/../data/bookings.json' → /srv/bookbay/data/bookings.json

Absolute and relative paths: an absolute path starts at the root and means the same file wherever it's used: /srv/bookbay/data/bookings.json. A relative path doesn't start with /, like data/bookings.json, and PHP joins it to the current working directory — the folder PHP was started in, which getcwd() shows. For a web request that's usually the folder of the script; for a cron job, it's often the user's home folder. So the same relative path finds the file in one case and not in the other — today's bug. .. means "one folder up" and . means "this folder".

The same relative path, two working directories
# The booking page, served from /srv/bookbay/public
$ cd /srv/bookbay/public && php -r 'echo getcwd(), PHP_EOL; var_dump(is_file("../data/bookings.json"));'
/srv/bookbay/public
bool(true)
# The reminder script, started by cron from the home folder
$ cd ~ && php -r 'echo getcwd(), PHP_EOL; var_dump(is_file("../data/bookings.json"));'
/home/bookbay
bool(false)

Paths from the script's own folder: the magic constant __DIR__ (Act 03) is the absolute path of the folder containing the current file, whatever the working directory. Build every path from it: __DIR__ . '/../data/bookings.json' in public/book.php always means /srv/bookbay/data/bookings.json. Better still, define the project root once — const ROOT = __DIR__ . '/..'; in a config file, or dirname(__DIR__) — and build every path from that. Composer's autoloader works the same way (Act 13).

Paths built from __DIR__
<?php
// public/book.php — works from any working directory
const ROOT = __DIR__ . '/..'; // the project root, defined once
$bookingsFile = ROOT . '/data/bookings.json';
$uploadsDir = dirname(__DIR__) . '/storage/uploads';
echo $bookingsFile, "\n";
echo $uploadsDir, "\n";
// on the server (in the Playground, __DIR__ is just /):
// /srv/bookbay/public/../data/bookings.json
// /srv/bookbay/storage/uploads

Taking paths apart: basename($path) returns the last part (photo.jpg), dirname($path) the folder above it (/srv/bookbay/uploads), and dirname($path, 2) two levels up. pathinfo($path) returns all of them at once, plus extension and filename (the name without the extension). Note that pathinfo() only looks at the text: photo.final.JPG has the extension JPG, in capitals, and the file doesn't even need to exist. realpath() is different: it asks the disk, removes every . and .., follows links, and returns the real absolute path — or false if the file doesn't exist. Chapter 7 uses it to stop path traversal attacks.

Taking a path apart
<?php
$path = '/srv/bookbay/uploads/photo.final.JPG';
echo basename($path), "\n"; // photo.final.JPG
echo dirname($path), "\n"; // /srv/bookbay/uploads
echo dirname($path, 2), "\n"; // /srv/bookbay
print_r(pathinfo($path));
mkdir('/tmp/bookbay/data', 0775, true);
file_put_contents('/tmp/bookbay/data/bookings.json', '[]');
var_dump(realpath('/tmp/bookbay/data/../data/./bookings.json'));
var_dump(realpath('/tmp/bookbay/missing.json'));
// Array ( [dirname] => /srv/bookbay/uploads [basename] => photo.final.JPG [extension] => JPG [filename] => photo.final )
// string(31) "/tmp/bookbay/data/bookings.json"
// bool(false)

Checking files: file_exists($path) is true for files and folders; is_file() only for files and is_dir() only for folders. is_readable() and is_writable() check permissions (chapter 2). Checking first turns a confusing warning into a clear message: "The bookings file is missing" instead of "Failed to open stream". One detail: PHP caches these answers within a request for speed. If the same request creates or deletes a file and checks again, call clearstatcache() first. The table below compares the checks.

Table — Checking a path
FunctionTrue for a file?True for a folder?False when…
file_exists($p)YesYesNothing is there
is_file($p)YesNoMissing, or a folder
is_dir($p)NoYesMissing, or a file
is_readable($p)If PHP may read itIf PHP may list itMissing or no permission
is_writable($p)If PHP may change itIf PHP may create files in itMissing or no permission
Checking before using
<?php
$dir = '/tmp/bookbay/data';
$file = "$dir/bookings.json";
@mkdir($dir, 0775, true);
file_put_contents($file, '[]');
var_dump(file_exists($file), is_file($file), is_dir($file)); // true, true, false
var_dump(file_exists($dir), is_file($dir), is_dir($dir)); // true, false, true
var_dump(is_readable($file), is_writable($dir));
if (!is_file("$dir/holidays.json")) {
echo "The holiday list is missing: using no holidays\n";
}

Paths in other languages: Python has pathlib, where a path is an object: Path(__file__).parent / "data" / "bookings.json", with methods like .exists() and .suffix. Java has java.nio.file.Path and C# System.IO.Path. PHP doesn't support a built-in path object — paths are plain strings and the functions above work on them. SplFileInfo (chapter 3) comes closest, and libraries like Symfony's Filesystem component add helpers such as Path::join().

Key Takeaway

Files live in a tree of folders starting at the root (/ on Linux; C:\ per drive on Windows, where PHP accepts / too). Absolute paths start at the root and mean the same file everywhere; relative paths are joined to the current working directory, which depends on how PHP was started — so build every path from __DIR__ or a project root defined once. basename(), dirname() and pathinfo() split path text; realpath() asks the disk and resolves .. and links, returning false for missing files. file_exists() covers files and folders, is_file()/is_dir() one each, is_readable()/is_writable() permissions — and clearstatcache() refreshes PHP's cached answers. PHP has no built-in path object like Python's pathlib.

Why This Matters

Wrong paths are the most common reason a PHP feature works on one machine or in one way of running, and fails in another: a cron job, a queue worker, a test run. Building paths from __DIR__ removes the whole category of bugs.

Every framework defines its paths this way: Laravel's base_path(), storage_path() and public_path() are exactly "the project root, defined once, plus a folder".

Both scripts now use ROOT . '/data/bookings.json' and find the same file. Next, Mia has to actually read and write it — and the reminder script, running as a different system user, gets "Permission denied" when it tries to update the file. That's the next chapter: reading, writing and permissions.