Search code examples
phpmkdir

PHP Mkdir if folder doesn't exist, if it does continue but add an incrementing value to the name each time


I'm checking to see if a folder exists by using the file_exists function.

If it doesn't, I'm creating a set of folders.

If it does exist, I want it to carry on creating the folders but the top folder should increment an id #1 , #2 , #3 etc each time.

if (file_exists('temp/$email')) {
    mkdir("temp/$email/");  
    mkdir("temp/$email/css");  
    mkdir("temp/$email/js");  
    mkdir("temp/$email/images"); 

} else {

    $version = 0;
    $version++;

    mkdir("temp/$email$version/");  
    mkdir("temp/$email$version/css");  
    mkdir("temp/$email$version/js");  
    mkdir("temp/$email$version/images"); 
}

Something along the lines of this but obviously that won't work. How can I go about doing this?

Also - is there a cleaner / simpler way of doing multiple mkdirs instead of writing them out in a long list like how I've done?


Solution

  • Here's a slightly more efficient solution for you, also handles creating the subdirectories without a big list of mkdir.

    You can define subdirectories like a/deeper/sub/directory and it will create the full path.

    Some default values to make the code work:

    define('BASE_DIR', 'temp/');
    
    $email = 'hello';
    
    $subdirs = array(
        'css',
        'js',
        'images'
    );
    

    Improved loop:

    $version = '';
    
    if (file_exists(BASE_DIR . $email)) {
        $version = 0;
        while (file_exists(BASE_DIR . $email . (++$version)));
    }
    

    Create your subdirectories:

    foreach ($subdirs as $dir) {
        mkdir(BASE_DIR . $email . $version . '/' . $dir, 0777, true);
    }