How to use PHP mkdir function recursively to skip existing directory and to create new one?

2k views Asked by At

How to use PHP mkdir function recursively to skip existing directory and to create new one from the string $pathname

// works fine if directories don't exist
mkdir($root_dir . '/demo/test/one', 0775, true);

// It will throw error - Message: mkdir(): File exists
mkdir($root_dir . '/demo/test/two', 0775, true);

What is the solution?

2

There are 2 answers

0
Ali On BEST ANSWER

Your code should work as it is, the problem happens when/if you run it for the second time as per @chris85's suggestion you can check if their exists beforehand.

<?php
// given
$root_dir = __DIR__;

// and you want to have these
$dirs = [
    $root_dir . '/demo/test/one',
    $root_dir . '/demo/test/tow',
    $root_dir . '/demo/test/three',
    $root_dir . '/demo/test/four',
    $root_dir . '/demo/test/and/so/on',
];

// just check if they're not exists and then create them
foreach ($dirs as $dir) {
    if (!is_dir($dir)) {
        mkdir($dir, 0775, true);
    }
}
0
Stefan On

Check with is_dir if the directory already exists:

if(!is_dir($pathname)) { 
   mkdir($pathname, 0775, true);
}