Master PHP’s is_dir(): Quick Guide to Checking Directories and Traversing Files
This article explains PHP's is_dir() function, showing how to determine whether a path is a directory, why it matters for file management, and provides clear code examples for simple checks and recursive directory traversal.
PHP is a popular server‑side scripting language with a rich function library. 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.
Below is a basic example that checks a single path:
<?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";
}
?>The example shows that $dir holds the path string, and is_dir() returns true for directories and false otherwise.
When using is_dir(), ensure the path exists and is accessible; otherwise the function will fail.
Beyond simple checks, is_dir() can be used for more complex tasks like traversing a directory’s contents. The following code demonstrates how to iterate through all files and sub‑directories:
<?php
$dir = "path/to/directory";
// Check if the path is a directory
if (is_dir($dir)) {
// Open the directory
if ($dh = opendir($dir)) {
// Read entries
while (($file = readdir($dh)) !== false) {
// Skip . and ..
if ($file == "." || $file == "..") {
continue;
}
$path = $dir . '/' . $file;
// Determine if entry is a directory
if (is_dir($path)) {
echo "{$path} is a directory";
} else {
echo "{$path} is a file";
}
}
// Close the directory
closedir($dh);
}
} else {
echo "Path {$dir} is not a directory";
}
?>This script first verifies the path, opens it with opendir(), reads entries with readdir(), skips the special entries “.” and “..”, builds each entry’s full path, and uses is_dir() again to distinguish files from directories before closing the handle with closedir().
Summary
The article presented the PHP is_dir() function, its syntax, basic usage, and practical examples for both simple directory checks and recursive traversal, demonstrating how it facilitates precise file operations and management.
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.
