php.is_dir()
When working with files and directories, it may be essential to actually verify that the specified file is a directory. For example, when iterating through a directory, it can be useful to check that you are processing files and not subdirectories.
In this post, we will learn how to use the is_dir()
function to check if a given file is a directory or a regular file.
PHP is_dir() Function
As the name suggests, the is_dir
function allows us to tell whether a given filename is a directory or not.
The function syntax is as shown:
is_dir(string $filename): bool
The function accepts one parameter:
filename
- denotes the path to the filename you wish to check. If the specifiedfilename
is a symbolic or hard link then the link will be resolved and checked.
The function will then return a Boolean value with true
denoting the file is a directory and false
denoting otherwise.
Example
The following snippet demonstrates how to use the is_dir()
to check if a given file is a directory.
$path = '/path/to/directory';
if (is_dir($path)) {
echo "$path is a directory";
} else {
echo "$path is not a directory";
}
In this example, the is_dir()
function allows us to check if the $path
variable points to a directory. If it does, we print the message path/to/directory
otherwise, the message path/to/directory is not a directory
is printed.
Conclusion
In this post, you learned how to use the is_dir()
function to check whether an input file is a directory or not.