PHP is_dir() Function

PHP is_dir() Function

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.

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.

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:

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

Table of Contents
Great! Next, complete checkout for full access to GeekBits.
Welcome back! You've successfully signed in.
You've successfully subscribed to GeekBits.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.