Using PHP is_dir() to Check Directories and Traverse Files
This article explains PHP's is_dir() function, demonstrates how it checks whether a path is a directory, provides simple and advanced code examples—including directory traversal with opendir() and readdir()—and offers practical usage tips for developers.
PHP is a popular server‑side scripting language with a rich function library. This article introduces the commonly used is_dir() function, which determines whether a given path is a directory and returns a boolean.
The function is useful in many scenarios such as file‑management systems where you need to distinguish files from folders.
Example 1 shows a simple check:
<?php
$dir = "path/to/directory";
// 判断路径是否为目录
if (is_dir($dir)) {
echo "路径 {$dir} 是一个目录";
} else {
echo "路径 {$dir} 不是一个目录";
}
?>The script assigns a path to $dir, calls is_dir($dir), and echoes whether the path is a directory.
When using is_dir(), ensure the path exists and is accessible; otherwise the function cannot operate correctly.
Beyond simple checks, is_dir() can be combined with opendir(), readdir(), and closedir() to traverse a directory tree, as demonstrated in Example 2.
<?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} 是一个目录";
} else {
echo "{$path} 是一个文件";
}
}
// 关闭目录
closedir($dh);
}
} else {
echo "路径 {$dir} 不是一个目录";
}
?>The second example opens the directory, iterates over entries, skips “.” and “..”, builds full paths, and uses is_dir() to differentiate sub‑directories from files, printing appropriate messages.
In summary, the is_dir() function is a practical tool for PHP developers to verify directory paths and to build more complex file‑system operations.
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.
