What is PHP is_dir() Function?
To check whether a path is a directory or not, use is_dir() function. In other words, this function also declares the existence of the directory. “is_dir” is short for “is directory”.
Syntax:
is_dir(path)
Parameters:
The Function has 1 parameter which is required-
path (Required): it is the path to the file that you want to check whether it is directory or not. The function checks the path relative to the current directory. If you mention a hard link or symbolic link as path, then the function resolves and check it.
Return Values:
The function returns-
- TRUE – if the path mentioned as parameter is a directory. Check example 1.
- FALSE – if the path filename in the parameter is not a directory. Check example 1.
How to use is_dir() in coding?
As the function returns a Boolean value TRUE/FALSE, you can check this by conditional statements i.e. if statement, ternary operator. Choose one that suits your requirement. Depending on the result that the conditional statement returns, your program flow progresses. Look at the code below-
<?php
if (is_dir("images/")) {
echo 'This is a directory.';
} else {
echo ' This is not a directory.';
}
?>
Examples:
Example 1:
<?php
var_dump(is_dir("image"));
echo "<br />";
var_dump(is_dir("fakefoleder"));
?>
Output:
bool(true)
bool(false)
Explanation:
Line 2: the directory “image” exists in the current directory, so, the function returns TRUE.
Line 4: the directory “fakefolder” doesn’t exist in the current directory, so, the function returns FALSE.
Notes on is_dir() Function:
- . (single dot) indicates current directory and .. (double dots) indicates parent directory. So, if you use them as paths, the function returns TRUE.
- The function doesn’t consider a web address as a directory. So, it returns “php.net is not a directory” in the following example-
Caution:
PHP cache the result of the is_dir() function. So if you call this function multiple times in a script PHP sends you the cached result. The problem is if existence of the directory, you won’t get the up-to-date result. To get the latest result, clear the cache with clearstatcache() function. Check the code below-
<?php
$path = "js/";
var_dump(is_dir($path));
// Some codes.
var_dump(is_dir($path));
// Some codes.
clearstatcache();
var_dump(is_dir($path));
// Some codes.
?>
PHP Version Support:
PHP 4, PHP 5, PHP 7, PHP 8
Summary: PHP is_dir() Function
When you work with files and directories, you may need to check whether a path is a directory or not. The is_dir() function helps you to know this which is a built-in filesystem function in PHP.