Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Files and I/O

PHP is_dir() and mkdir() functions

Reference for PHP is_dir(), mkdir() and rmdir(): test for a directory, create nested folders with recursive mode, permissions, the failure cases and safe patterns.

is_dir() tells you whether a path is an existing directory. mkdir() creates one, and with its recursive argument it creates every missing parent too. rmdir() removes a directory, but only when it is empty.

These three cover most day-to-day folder work: make sure an output directory exists, then clean it up afterwards. They report problems with a warning and a false return value instead of exceptions.

PHP
if (!is_dir($dir)) {
    mkdir($dir, 0777, true);
}

Try it

PHP Creating nested directories

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP An idempotent ensureDirectory()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
is_dir(string $filename): bool
mkdir(string $directory, int $permissions = 0777, bool $recursive = false, ?resource $context = null): bool
rmdir(string $directory, ?resource $context = null): bool
Name Description
$filename / $directory The path to test, create or remove.
$permissions Mode for a new directory; the process umask is subtracted. Ignored on Windows.
$recursive If true, create missing parent directories as well.

Return value: is_dir() returns a boolean. mkdir() and rmdir() return true on success and false (with a warning) on failure.

Usage notes

  • mkdir() fails if the directory already exists, with a warning. Test with is_dir() first or use the pattern shown above.
  • Without recursive, parents must exist. Creating a/b/c when a is missing fails.
  • Race-safe creation. Another process may create the directory between your check and mkdir(). Re-check with is_dir() after a failed mkdir() before giving up.
  • rmdir() needs an empty directory. Delete the files first (see unlink(), scandir()); there is no built-in recursive delete.
  • Permissions: 0777 is the usual argument; the umask usually turns it into 0755. Avoid world-writable folders for anything sensitive.
  • Symlinks: is_dir() follows a link to a directory and reports true; rmdir() on a link may fail, use unlink() for links.
  • Results are cached for the request. Call clearstatcache() after changing directories by other means.
  • A file is not a directory: is_dir() is false for regular files, while file_exists() is true for both.