PHP Directory Functions
In this page:
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
mkdir("sample_dir");
$items = scandir("sample_dir");
print_r($items);
?>
Login to try C/C++/Java/PHP code in the editor
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
mkdir("sample_dir");
var_dump(is_dir("sample_dir"));
var_dump(file_exists("sample_dir"));
?>
Login to try C/C++/Java/PHP code in the editor
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
mkdir("parent/child", 0755, true);
echo is_dir("parent/child") ? "Created including parent" : "Failed";
?>
Login to try C/C++/Java/PHP code in the editor
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
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);
?>
Login to try C/C++/Java/PHP code in the editor
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
mkdir("empty_dir");
rmdir("empty_dir");
echo file_exists("empty_dir") ? "Still exists" : "Removed successfully";
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: