How to create a folder only if it doesn’t exist

How to create a folder only if it doesn’t exist

Solution 1:

You can create a directory using mkdir(), checking first if it exists:


if (!file_exists('path/to/directory')) {
    mkdir('path/to/directory', 0777, true);
}

✅ Notes:

The 0777 mode is the default for directories, but the actual permissions may be affected by the system’s umask.

The third parameter true allows recursive creation (e.g., if parent directories don’t exist).

Solution 2:

When creating nested directories, you need to set the recursive flag (third argument) to true:


mkdir('path/to/directory', 0755, true);

Explanation:

0755 → Common permission setting for directories (owner full access, others read/execute).

true → Ensures that any missing parent directories are created as well.

Solution 3:

For a more universal approach, you can use a recursive function to create a full directory path:


/**
 * Recursively create a directory path
 */
function createPath($path) {
    if (is_dir($path)) {
        return true;
    }

    $prevPath = substr($path, 0, strrpos($path, '/', -2) + 1);
    $created  = createPath($prevPath);

    return ($created && is_writable($prevPath)) ? mkdir($path) : false;
}

✅ How it works:

If the directory already exists, it returns true.

Otherwise, it walks up the directory tree until it finds an existing folder.

It then works its way back down, creating directories one by one.

Returns true on success, false on failure.

⚠️ Possible Improvements:

Add a stopping level (e.g., don’t go above the user’s home directory).

Include a permissions parameter to control the mode for newly created directories.

Feel Free To Message Us