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.
if (!is_dir($dir)) { mkdir($dir, 0777, true); }
Try it
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.
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
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 withis_dir()first or use the pattern shown above.- Without
recursive, parents must exist. Creatinga/b/cwhenais missing fails. - Race-safe creation. Another process may create the directory between your check and
mkdir(). Re-check withis_dir()after a failedmkdir()before giving up. rmdir()needs an empty directory. Delete the files first (seeunlink(),scandir()); there is no built-in recursive delete.- Permissions:
0777is the usual argument; the umask usually turns it into0755. Avoid world-writable folders for anything sensitive. - Symlinks:
is_dir()follows a link to a directory and reportstrue;rmdir()on a link may fail, useunlink()for links. - Results are cached for the request. Call
clearstatcache()after changing directories by other means. - A file is not a directory:
is_dir()isfalsefor regular files, whilefile_exists()istruefor both.