← Back to PHP Course | Chapter 9: File Handling | Lesson 6 of 8

PHP Directory Functions

Creating Directories

scandir($path) returns an array of every file and subdirectory name inside a given directory, including the special '.' and '..' entries that represent the current and parent directory.

Example: Creating Directories

php
<?php
mkdir("sample_dir");
$items = scandir("sample_dir");
print_r($items);
?>

Removing Directories

is_dir() and file_exists() let you check whether a given path is a directory or exists at all before you try to read from or write to it, avoiding warnings from operating on a path that isn't there.

Example: Removing Directories

php
<?php
mkdir("sample_dir");
var_dump(is_dir("sample_dir"));
var_dump(file_exists("sample_dir"));
?>

Listing Directory Contents

mkdir($path) creates a new directory, and passing true as the third argument (recursive) lets it create any missing parent directories along the way in a single call.

Example: Listing Directory Contents

php
<?php
mkdir("parent/child", 0755, true);
echo is_dir("parent/child") ? "Created including parent" : "Failed";
?>

Working Directories

glob($pattern) finds all paths matching a wildcard pattern like '*.php', which is often more convenient than scandir() plus manual filtering when you only care about files of a specific type.

Example: Working Directories

php
<?php
mkdir("sample_dir");
file_put_contents("sample_dir/a.php", "");
file_put_contents("sample_dir/b.txt", "");
$phpFiles = glob("sample_dir/*.php");
print_r($phpFiles);
?>

Checking Directories

rmdir() removes an empty directory, but will fail on a directory that still contains files — deleting a non-empty directory tree requires recursively deleting its contents first.

Example: Checking Directories

php
<?php
mkdir("empty_dir");
rmdir("empty_dir");
echo file_exists("empty_dir") ? "Still exists" : "Removed successfully";
?>
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.