0Pricing
PHP Academy · Lesson

Working with Directories

List, create, and delete directories with scandir and mkdir.

Working with Directories is a free PHP Academy lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Directory Operations in PHP

PHP provides functions to list, create, navigate, and delete directories on the server:

  • scandir() — list directory contents
  • mkdir() — create directory
  • rmdir() — remove empty directory
  • glob() — find files matching a pattern

scandir()

List all files and directories in a directory:

<?php
$entries = scandir('/var/www/html/uploads');

// scandir includes '.' and '..'
$entries = array_diff($entries, ['.', '..']);

foreach ($entries as $entry) {
    echo $entry . PHP_EOL;
}

glob() Pattern Matching

glob() returns files matching a shell-style pattern:

<?php
// Find all PHP files in a directory
$phpFiles = glob('/var/www/html/*.php');

// Recursively with GLOB_BRACE
$logs = glob('/var/log/{app,error,access}.log', GLOB_BRACE);

foreach ($phpFiles as $file) {
    echo basename($file) . PHP_EOL;
}

mkdir() and Permissions

Create one or multiple nested directories:

<?php
$dir = '/var/www/uploads/2024/05';

// Create nested directories in one call:
if (!is_dir($dir)) {
    mkdir($dir, 0755, true);  // true = recursive
    echo "Created: $dir";
}

Deleting Directories

rmdir() only removes empty directories. To delete with contents, use a recursive function:

<?php
function deleteDir(string $path): void {
    foreach (scandir($path) as $entry) {
        if ($entry === '.' || $entry === '..') continue;
        $full = $path . DIRECTORY_SEPARATOR . $entry;
        is_dir($full) ? deleteDir($full) : unlink($full);
    }
    rmdir($path);
}

deleteDir('/tmp/old_cache');

Directory Iteration with DirectoryIterator

OO way to iterate directory contents:

<?php
$dir = new DirectoryIterator('/var/www/html/images');

foreach ($dir as $info) {
    if ($info->isDot()) continue;
    echo $info->getFilename();
    echo ' (' . $info->getSize() . ' bytes)';
    echo PHP_EOL;
}

RecursiveDirectoryIterator

Recursively iterate all files in a directory tree:

<?php
$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator('/var/www/src')
);

foreach ($iterator as $file) {
    if ($file->isDot()) continue;
    if ($file->getExtension() === 'php') {
        echo $file->getPathname() . PHP_EOL;
    }
}

getcwd and chdir

Get and change the current working directory:

<?php
$originalDir = getcwd();
echo 'Current: ' . $originalDir . PHP_EOL;

chdir('/var/www/html');
echo 'Changed to: ' . getcwd() . PHP_EOL;

// Restore
chdir($originalDir);
echo 'Restored: ' . getcwd() . PHP_EOL;

Path Manipulation

Build and parse file paths with portable constants and functions:

<?php
// DIRECTORY_SEPARATOR = '/' on Unix, '\\' on Windows
$base    = '/var/www/app';
$subPath = 'uploads' . DIRECTORY_SEPARATOR . 'images';
$full    = $base . DIRECTORY_SEPARATOR . $subPath;

echo realpath($full);  // resolves symlinks

// __DIR__ is the directory of the current file
$configPath = __DIR__ . '/../config/settings.json';
echo realpath($configPath);

Disk Space

Check available and total disk space:

<?php
$path = '/var/www';

$free  = disk_free_space($path);
$total = disk_total_space($path);
$used  = $total - $free;

echo 'Used: ' . round($used / 1024**3, 2) . ' GB';
echo 'Free: ' . round($free / 1024**3, 2) . ' GB';
echo 'Total: ' . round($total / 1024**3, 2) . ' GB';

SPL Temp Directory

Always use sys_get_temp_dir() to find the correct temp directory across platforms:

<?php
$tmpDir = sys_get_temp_dir();
echo 'Temp dir: ' . $tmpDir;

// Create a unique temporary directory
$uniqueDir = $tmpDir . DIRECTORY_SEPARATOR . 'myapp_' . uniqid();
mkdir($uniqueDir, 0700);

// ... use directory ...
// cleanup when done

Quick Check

Which PHP function recursively creates nested directories in a single call?

Recap: Working with Directories

Directory operations:

  • scandir() — list contents (includes . and ..)
  • glob() — find files by pattern
  • mkdir($path, 0755, true) — recursive creation
  • rmdir() — remove empty dir
  • RecursiveDirectoryIterator for deep traversal
  • __DIR__ and DIRECTORY_SEPARATOR for portable paths

Frequently asked questions

Is the “Working with Directories” lesson free?

Yes — the full text of “Working with Directories” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.

What will I learn in “Working with Directories”?

List, create, and delete directories with scandir and mkdir. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start PHP Academy?

No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Working with Directories” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this PHP Academy lesson?

Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Reading Files with PHP
  2. Writing and Appending to Files
  3. Working with Directories
  4. Handling File Uploads
← Back to PHP Academy