0

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?

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

1
if (file_exists('temp/'.$email)) {
    $version = 1;
    while (file_exists('temp/'.$email.$version)) {
        $version ++;
    }
} else {
    $version = "";
}
mkdir("temp/".$email.$version."/");  
// etc

You should put a sanity check there too, to make sure you don't get an infinite loop.

2 Comments

lovely. I'll give this a try in a bit then come back and give you the answer :) thanks!
Make sure to grab the latest-edited version - the old one would have had one of theose infinite loops I mentioned ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.