Master PHP’s is_dir(): Quick Guide to Checking Directories
This article explains PHP's is_dir() function, shows how to use it for simple directory checks and for traversing folder structures, provides complete code examples, and highlights important considerations such as path existence and permissions.
PHP is a popular server‑side scripting language. This article introduces the commonly used is_dir() function, which checks whether a given path is a directory and returns a boolean.
The function is useful in many scenarios, such as distinguishing files from folders in a file‑management system.
Basic usage
<?php
$dir = "path/to/directory";
// Check 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 the path exists and is accessible; otherwise the function will fail.
Traversing a directory
<?php
$dir = "path/to/directory";
// Check if the path is a 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 example first checks the path, opens the directory with opendir(), reads entries with readdir() while skipping “.” and “..”, determines each entry’s type with is_dir(), and finally closes the handle with closedir().
Summary
The is_dir() function allows PHP developers to easily determine whether a path is a directory, enabling both simple checks and more complex directory traversal tasks.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
php Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
