1
if(!empty($_POST['newdir'])) {
    $dir_base= preg_replace("/[^a-zA-ZÀ-ÿ0-9\s]/",'',$_POST['newdir']);
    $dir_path=$pattern.$dir_base;
    $dir_path_lwr = strtolower($dir_path);

    $old_dirs = glob($pattern.'*', GLOB_ONLYDIR);
    $old_dirs_lwr = array_map('strtolower', $old_dirs);

    $i = 1;
    $cond = true;
    while($cond) {

        if(in_array($dir_path_lwr, $old_dirs_lwr)) {
            $i++;
            $new_base=$dir_base.' '.$i.'';
            $new_path= $pattern.$new_base;
            $dir_path_lwr = strtolower($new_path);
        }
        elseif(!in_array($dir_path_lwr, $old_dirs_lwr)) {
            mkdir($dir_path, 0755);
            $cond = false;
        }
    }
}

EDIT Have changed the above to the most recent version. For testing, I am now simply echoing out the $cond var rather than creating directories all over the place. The 'Not In' argument works fine - when a duplicate name IS found, the page takes about 10 to 12 seconds to load, before white screening. There's something wrong with my while loop i think...

What I'm trying to do is:

  • Submit a new directory name to the script
  • Clean and escape that name
  • Check it against existing directories in that location ($pattern)
  • If there is no conflict, create the directory (works)
  • If there is a conflict, append a number (eg, My Directory 2) and then create the directory (doesn't work)

So, basically how to check against existing file names, and create a uniquely name directory dynamically. All help appreciated :)

Eamonn
  • 1,338
  • 2
  • 21
  • 53
  • You can also find some alternative methods in this very similar question: http://stackoverflow.com/q/1707801/176974 – jap1968 Mar 06 '15 at 09:23

1 Answers1

1

Fixed it - i was confusing the vars within the loop.

Posting for future reference:

if(!empty($_POST['newdir'])) {
    $dir_base= preg_replace("/[^a-zA-ZÀ-ÿ0-9\s]/",'',$_POST['newdir']);
    $dir_path=$pattern.$dir_base;
    $dir_path_lwr = strtolower($dir_path);

    $old_dirs = glob($pattern.'*', GLOB_ONLYDIR);
    $old_dirs_lwr = array_map('strtolower', $old_dirs);

    $i = 1;
    $cond = true;
    while($cond) {

        if(in_array($dir_path_lwr, $old_dirs_lwr)) {
            $i++;
            $new_base=$dir_base.' '.$i.'';
            $dir_path= $pattern.$new_base;
            $dir_path_lwr = strtolower($dir_path);
        }
        elseif(!in_array($dir_path_lwr, $old_dirs_lwr)) {
            mkdir($dir_path, 0755);
            $cond = false;
        }
    }
}
Eamonn
  • 1,338
  • 2
  • 21
  • 53