Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to create a directory

Short answer

Check that the folder does not exist yet and create it:

<?php
 
$dir = sys_get_temp_dir() . '/recipe-dir-' . uniqid();
 
if (!is_dir($dir)) {
    mkdir($dir);
}
 
var_dump(is_dir($dir));

Output:

bool(true)

Nested folders

A third argument of true creates the whole chain of folders:

<?php
 
$dir = sys_get_temp_dir() . '/recipe-' . uniqid() . '/2026/03';
 
mkdir($dir, 0775, true);
 
var_dump(is_dir($dir));

Output:

bool(true)

Without the check — a warning

If the folder already exists, mkdir() emits a warning and returns false. So is_dir() is always called first.

Functions used in this recipe

  • mkdir — Creates a folder.
  • is_dir — Checks whether a path is a folder.
  • is_writable — Checks whether a file or folder can be written to.

Thanks for reading!

Donate to the site — we work hard for you.