dir()
PHP is a popular server-side scripting language that is used to create dynamic web pages. One of the essential functions in PHP is the directory function, which
Introduction
This chapter covers how to work with directories in PHP: opening, reading, creating, and deleting them, plus the now-removed dir() function and its modern replacements. PHP ships with a full set of built-in functions for these tasks, so you can list the contents of a folder, walk a directory tree, or clean up files without shelling out to the operating system.
You will most often need directory functions when building an upload manager, generating a file listing for a download page, cleaning up temporary files, or scanning a folder of templates or images at runtime.
Understanding Directory Functions in PHP
PHP groups directory work into a handful of procedural functions, plus an object-oriented DirectoryIterator class. The most common ones are:
opendir()— opens a directory and returns a handle (a resource you read from)readdir()— reads the next entry from an open directory handleclosedir()— closes a directory handle and frees the resourcescandir()— reads every entry into an array in one callglob()— returns paths matching a shell wildcard patternmkdir()— creates a new directoryrmdir()— deletes an empty directoryis_dir()— checks whether a path is a directory
Every directory listing in PHP includes the special entries . (the directory itself) and .. (its parent). You almost always want to skip these — forgetting to is a common source of bugs.
Using opendir() and readdir() to Read a Directory
opendir() opens a directory and returns a directory handle. You then pass that handle to readdir(), which returns the name of the next entry each time you call it, and false when there are no more entries. Always close the handle with closedir() when you are done.
Because readdir() can legitimately return "0" (a file literally named 0), compare its result with !== false rather than a loose check, so a falsy filename is not mistaken for the end of the list.
Example of opendir() and readdir() in PHP
<?php
$dir = "/path/to/directory";
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if ($file === "." || $file === "..") {
continue; // skip self and parent
}
echo "filename: " . $file . PHP_EOL;
}
closedir($dh);
}
}For a directory containing a.txt, b.log, and report.csv, this prints:
filename: b.log
filename: report.csv
filename: a.txtThe order is not alphabetical — readdir() returns entries in the order the filesystem stores them. If you need a predictable order, use scandir() (which sorts) or sort the results yourself.
Using scandir() to List a Directory at Once
scandir() reads the entire contents of a directory into an array in a single call, and — unlike readdir() — it sorts the result alphabetically by default. This is the most convenient way to get a sorted list of files. It still includes . and .., so filter them out when you only want real files.
Using scandir() Function in PHP
<?php
$dir = "/path/to/directory";
$files = scandir($dir);
print_r($files);For a directory containing a.txt, b.log, and report.csv, the output is:
Array
(
[0] => .
[1] => ..
[2] => a.txt
[3] => b.log
[4] => report.csv
)Pass SCANDIR_SORT_DESCENDING as the third argument to reverse the order, or SCANDIR_SORT_NONE to skip sorting (which is faster for very large directories).
Matching Files with glob()
When you only want files that match a pattern — all .txt files, or everything starting with report — glob() is the cleanest option. It accepts a shell wildcard pattern and returns an array of matching paths:
<?php
foreach (glob("/path/to/directory/*.txt") as $file) {
echo $file . PHP_EOL;
}If only a.txt matches in our sample directory, this prints:
/path/to/directory/a.txtUnlike scandir(), glob() does not include . and .., and it returns full paths rather than bare filenames.
Creating Directories with mkdir()
The mkdir() function creates a new directory. Its first argument is the path, the second sets the permissions (an octal value such as 0755), and the optional third argument, when true, creates any missing parent directories recursively.
Using mkdir() Function in PHP
mkdir("/path/to/my/new/directory", 0755, true);Without the true flag, mkdir() fails with a warning if a parent directory does not already exist. On Unix-like systems the actual permissions are also affected by the process umask.
Deleting Directories with rmdir()
The rmdir() function deletes a directory. It takes the path of the directory you want to remove.
Using rmdir() Function in PHP
rmdir("/path/to/my/new/directory");Note: rmdir() only removes empty directories. To delete a directory that still contains files, remove the files (and any sub-directories) first — for example by iterating the contents with scandir() and calling unlink() on each file.
The Modern Replacement: DirectoryIterator
For object-oriented code, the SPL DirectoryIterator class is the recommended way to walk a directory. It is iterable with foreach and gives you rich information about each entry — its name, size, type, and modification time — without separate function calls:
<?php
foreach (new DirectoryIterator("/path/to/directory") as $entry) {
if ($entry->isDot()) {
continue; // skip "." and ".."
}
echo $entry->getFilename() . PHP_EOL;
}For a directory containing a.txt, b.log, and report.csv, this prints:
b.log
report.csv
a.txtisDot() conveniently skips both . and .. in one check. To walk an entire directory tree, including sub-folders, use RecursiveDirectoryIterator together with RecursiveIteratorIterator.
The Legacy dir() Function
Deprecated: The
dir()function was deprecated in PHP 7.4 and removed in PHP 8.0. UseDirectoryIteratororscandir()instead. The example below is provided only for maintaining older code.
The dir() function returns a Directory object that provides an object-oriented way to read directory contents. Unlike scandir(), which returns a simple array, dir() returns an object with methods like read(), rewind(), and close(). Note that dir() is not an alias for scandir() — they serve different purposes and return different data types.
Using dir() Function in PHP (legacy)
<?php
$dir = dir("/path/to/directory");
while (($file = $dir->read()) !== false) {
echo "filename: " . $file . PHP_EOL;
}
$dir->close();Conclusion
PHP offers several ways to work with directories. Use scandir() or glob() for quick, sorted listings, the opendir()/readdir()/closedir() trio when you want to stream entries one at a time, and DirectoryIterator for clean object-oriented traversal. Create and remove folders with mkdir() and rmdir(), and reach for RecursiveDirectoryIterator when you need to descend into sub-directories. For a broader look at working with the filesystem, see the PHP Directory and PHP Filesystem chapters.