Working with Directories

3.Working with Directories

M

In this chapter

We'll learn how to create folders, including whole paths at once, how to copy, move and delete files, why rmdir() only removes empty folders and how to delete a whole tree safely, and how to list a folder with scandir(), glob(), DirectoryIterator and RecursiveDirectoryIterator.

14–16 min

The Problem in Real Life

Olivia's backup plan: every night, copy bookings.json to backups/2026/11/bookings-2026-11-06.json, delete backups older than 30 days, and email her the total size of the barbers' photos. Mia writes copy($file, "backups/2026/11/...") and gets "No such file or directory" — the folders 2026/11 don't exist yet.

Her clean-up script then tries rmdir('backups/2026/10') and gets "Directory not empty".

M

Creating a folder needs its parent, and deleting one needs it empty. Files are easy — folders have rules.

Mia

Folder Errors vs. Folder Tools

Whole paths at once

mkdir() with its third argument creates every missing parent folder.

Only empty folders

rmdir() refuses a folder with files in it; a tree is emptied from the bottom up.

Listing contents

scandir(), glob() and iterators list files — one folder or a whole tree.

Working with Directories

Folders as part of the data: backups, uploads and exports need folders created, listed and cleaned up by the code itself. This chapter covers:

  • Creating folders: mkdir() and permissions.
  • Copying, moving and deleting files: copy(), rename() and unlink().
  • Removing folders: rmdir() and deleting a whole tree.
  • Listing a folder: scandir() and glob().
  • Iterating: DirectoryIterator and RecursiveDirectoryIterator.

Creating folders: mkdir($path) creates one folder, and fails if its parent doesn't exist. mkdir($path, 0775, true) — with true as the third argument, recursive — creates every missing folder along the way, so backups/2026/11 appears in one call. The second argument is the permission mode (chapter 2); the server's umask may remove some bits from it. mkdir() warns and returns false if the folder already exists, so check first: if (!is_dir($path)) { mkdir($path, 0775, true); }.

Creating a whole path and copying a backup
<?php
$root = '/tmp/bookbay';
@mkdir("$root/data", 0775, true);
file_put_contents("$root/data/bookings.json", '[{"id":4811}]');
$backupDir = "$root/backups/" . date('Y/m', strtotime('2026-11-06'));
if (!is_dir($backupDir)) {
mkdir($backupDir, 0775, true); // creates backups, 2026 and 11
}
var_dump(copy("$root/data/bookings.json", "$backupDir/bookings-2026-11-06.json"));
print_r(scandir($backupDir));
// bool(true)
// Array ( [0] => . [1] => .. [2] => bookings-2026-11-06.json )

Copying, moving and deleting files: copy($from, $to) copies a file. rename($from, $to) moves it — to a new name, or to another folder — and replaces an existing file at $to. On the same disk, rename() is atomic: other code sees either the old file or the new one, never half of it, which chapter 6 uses for safe writes. unlink($path) deletes a file. All three return true or false with a warning. There's no recycle bin on a server: an unlink() is final.

Removing folders: rmdir($path) removes a folder only if it's empty; otherwise it warns "Directory not empty". To delete a whole tree, delete its contents first, from the bottom up: every file, then every folder once it's empty. The recursive iterator below does exactly that with CHILD_FIRST. Deleting trees is the most dangerous thing a script can do — always build the path from a known base, never from user input, and double-check it isn't empty or / before you start.

Listing a folder: scandir($dir) returns every name in a folder as an array, sorted — including the two special entries . (this folder) and .. (the parent), which you nearly always skip. glob($pattern) returns full paths matching a pattern: * matches any characters and ? one character, so glob("$dir/*.json") finds every JSON file and glob("$dir/bookings-2026-10-*.json") every October backup.

Table — Ways to list files
ToolReturnsIncludes . and ..?Goes into subfolders?
scandir($dir)Array of names, sortedYesNo
glob("$dir/*.json")Array of full paths matching a patternNoNo
new DirectoryIterator($dir)Objects with size, time, typeYes (isDot())No
RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir, SKIP_DOTS))Objects for the whole treeNo (SKIP_DOTS)Yes
glob() and rmdir() on a full folder
<?php
$dir = '/tmp/bookbay/backups/2026/10';
@mkdir($dir, 0775, true);
foreach (['01', '02', '03'] as $day) {
file_put_contents("$dir/bookings-2026-10-$day.json", '[]');
}
file_put_contents("$dir/notes.txt", 'keep');
print_r(array_map('basename', glob("$dir/bookings-2026-10-*.json")));
var_dump(@rmdir($dir)); // false: not empty
echo error_get_last()['message'], "\n";
// Array ( [0] => bookings-2026-10-01.json [1] => bookings-2026-10-02.json [2] => bookings-2026-10-03.json )
// bool(false)
// rmdir(/tmp/bookbay/backups/2026/10): Directory not empty

Iterating with SPL: for more than names, PHP's SPL has iterator classes. new DirectoryIterator($dir) gives one SplFileInfo-like object per entry, with methods such as getFilename(), getSize(), getMTime(), isDir() and isDot(). For a folder and everything inside it, wrap a RecursiveDirectoryIterator in a RecursiveIteratorIterator: with SELF_FIRST you get each folder before its contents — good for listing — and with CHILD_FIRST the contents before the folder — exactly the order needed to delete a tree. FilesystemIterator::SKIP_DOTS leaves out . and ... The diagram below shows the two orders.

SELF_FIRST vs. CHILD_FIRST on backups/

backups/2026/

contains 10/ and 11/

visiting order

SELF_FIRST

2026 → 2026/10 → its files → 2026/11 → its files

CHILD_FIRST

files of 10 → 2026/10 → files of 11 → 2026/11 → 2026

so

Use for listing

a folder appears before its contents

Use for deleting

a folder is empty by the time it's reached

Listing a tree, then deleting it bottom-up
<?php
$base = '/tmp/bookbay-photos';
@mkdir("$base/ben", 0775, true);
@mkdir("$base/leo", 0775, true);
file_put_contents("$base/ben/a1.jpg", str_repeat('x', 1200));
file_put_contents("$base/leo/b7.jpg", str_repeat('x', 800));
$tree = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($base, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::SELF_FIRST,
);
$total = 0;
foreach ($tree as $path => $info) {
echo str_replace($base, '', $path), $info->isDir() ? '/' : " ({$info->getSize()} bytes)", "\n";
$total += $info->isFile() ? $info->getSize() : 0;
}
echo "total: {$total} bytes\n";
$bottomUp = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($base, FilesystemIterator::SKIP_DOTS),
RecursiveIteratorIterator::CHILD_FIRST,
);
foreach ($bottomUp as $path => $info) {
$info->isDir() ? rmdir($path) : unlink($path);
}
rmdir($base);
var_dump(file_exists($base));
// /ben/
// /ben/a1.jpg (1200 bytes)
// /leo/
// /leo/b7.jpg (800 bytes)
// total: 2000 bytes
// bool(false)

Key Takeaway

mkdir($path, 0775, true) creates a whole path of folders (check is_dir() first, it warns if the folder exists). copy() copies, rename() moves and replaces — atomically on the same disk — and unlink() deletes for good. rmdir() only removes empty folders, so trees are deleted bottom-up with RecursiveIteratorIterator and CHILD_FIRST, from a path you built yourself. scandir() lists names including . and .., glob() matches patterns like *.json, and DirectoryIterator / RecursiveDirectoryIterator give file objects with size, time and type — SELF_FIRST for listing, CHILD_FIRST for deleting, SKIP_DOTS to drop . and ...

Why This Matters

Backups, exports, cache folders and uploads all create and clean up folders. A script that forgets to create a parent folder fails at 2 a.m.; one that deletes trees carelessly can wipe the wrong folder.

The SPL iterators are also how frameworks find files: test runners discover tests, and Composer's classmap scans folders for classes (Act 13) exactly this way.

The nightly backup runs, old backups are removed and Olivia gets her photo total. Then Marcus shows Mia the access log: 2.1 GB. Her file() call to count yesterday's requests runs out of memory, because it loads every line at once. That needs a different way of reading — piece by piece. That's the next chapter: file handles, streams and wrappers.