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:
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.
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.
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.