Current Location: Home> Latest Articles> How to Check if a Directory Exists in PHP with Examples

How to Check if a Directory Exists in PHP with Examples

M66 2025-10-24

How to Check if a Directory Exists in PHP

In daily PHP file operations, it is common to need to check whether a directory exists. For example, before creating files or folders, we usually need to verify if the directory already exists to avoid duplication or errors.

Using the is_dir() Function

PHP provides a built-in function is_dir() to determine if a directory exists. This function accepts a directory path as a parameter and returns a boolean value indicating whether the path is an existing directory.

Function Syntax

bool is_dir(string $directory)

Parameter Explanation

  • $directory: The directory path to check.

Return Values

  • Returns true if the directory exists.
  • Returns false if the directory does not exist or the path is not a directory.

Example Code

<?php
$directory = "my_directory";

if (is_dir($directory)) {
  echo "Directory \"{$directory}\" exists";
} else {
  echo "Directory \"{$directory}\" does not exist";
}
?>

Notes

  • is_dir() only checks whether the directory itself exists and does not examine files or subdirectories within it.
  • If the specified path is a file rather than a directory, the function returns false.
  • If the path does not exist, it also returns false.

Conclusion

With the is_dir() function, PHP developers can easily determine whether a path is an existing directory. This is very useful in scenarios like file uploads, log management, and cache directory creation.