Development

php.is_dir()

Captain Salem 1 min read

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:

  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.

Share
Comments
More from Cloudenv

Cloudenv

Developer Tips, Tricks and Tutorials.

Great! You’ve successfully signed up.

Welcome back! You've successfully signed in.

You've successfully subscribed to Cloudenv.

Success! Check your email for magic link to sign-in.

Success! Your billing info has been updated.

Your billing was not updated.