How to Check Whether a Path Is a File or a Directory in PHP?

In this article, we look at how we can determine whether a path is a file or a directory using PHP.

Using is_file() and is_dir()

You can simply check if the path you're checking is a file, by using PHP's is_file() function. For example:

is_file('/path/to/file.txt'); // bool(true)

is_file('/path/to/non-existent-file.txt'); // bool(false)

is_file('/is/a/directory'); // bool(false)

Similarly, you could use is_dir() function to check whether the given path is a directory or not. For example:

is_dir('/path/to/file.txt'); // bool(false)

is_dir('..'); // bool(true)

is_dir('/non-existent/dir'); // bool(false)

PHP caches the results of these functions for performance reasons. You can use the clearstatcache() function to clear the cache if you feel the need, for example in cases where within the same script, you might be deleting/changing a file.

Using pathinfo()

You can check the file extension with pathinfo() function to determine whether the given string is a directory or a file. This works because the function does not return an extension if the path does not have it. Consider the following examples:

pathinfo('/has/no/extension', PATHINFO_EXTENSION); // string(0) ""

pathinfo('/has/empty-extension.', PATHINFO_EXTENSION); // string(0) ""

pathinfo('/path/to/file.txt', PATHINFO_EXTENSION); // string(3) "txt"

pathinfo('/path/to/.env', PATHINFO_EXTENSION); // string(3) "env"

With this information, you could, for example, use pathinfo() inside if/else code block etc., to check for a file or a directory. For example:

if (pathinfo('/path/to/file.txt', PATHINFO_EXTENSION)) {
    // ...
} else {
    // ...
}

This method does not check whether a file or directory actually exists. It merely parses a file path string and extracts information about that path. If you also wish to check if a directory or a file actually exists, then you could combine this with file_exists() which checks whether a file or directory exists. Alternatively, you may also use is_file() and/or is_dir() functions instead.


This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.