Backend Development 4 min read

Using PHP's is_dir() Function to Check and Traverse Directories

This article explains PHP's is_dir() function, demonstrates how to determine whether a path is a directory, and provides practical code examples for simple checks and recursive directory traversal, highlighting important usage considerations for backend developers.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP's is_dir() Function to Check and Traverse Directories

PHP is a widely used server‑side scripting language, and the is_dir() function is a built‑in utility that checks whether a given path refers to a directory, returning a boolean result.

The function accepts a single argument—the path to be examined—and is commonly used in file‑management systems to distinguish between files and folders.

Below is a basic example that checks a single path:

<?php
$dir = "path/to/directory";

// Determine if the path is a directory
if (is_dir($dir)) {
    echo "Path {$dir} is a directory";
} else {
    echo "Path {$dir} is not a directory";
}
?>

Before calling is_dir() , ensure that the path exists and is accessible; otherwise the function will fail.

For more complex scenarios, such as traversing all files and sub‑directories, is_dir() can be combined with opendir() , readdir() , and closedir() :

<?php
$dir = "path/to/directory";

if (is_dir($dir)) {
    if ($dh = opendir($dir)) {
        while (($file = readdir($dh)) !== false) {
            if ($file == "." || $file == "..") {
                continue;
            }
            $path = $dir . '/' . $file;
            if (is_dir($path)) {
                echo "{$path} is a directory";
            } else {
                echo "{$path} is a file";
            }
        }
        closedir($dh);
    }
} else {
    echo "Path {$dir} is not a directory";
}
?>

This script first verifies that the target is a directory, opens it, iterates over each entry while skipping the special entries "." and "..", builds the full path, and then uses is_dir() again to decide whether each entry is a file or a sub‑directory.

In summary, the is_dir() function is a versatile tool for PHP developers, enabling both simple directory checks and more advanced directory traversal tasks, which are essential for reliable file handling in backend applications.

backendfile managementis_dirdirectory-check
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.