PassThePeas
12/8/2014 - 11:20 PM

Creates a directory. If it already exists (or a file of the same name), tries to create with the name suffixed by a number

Creates a directory. If it already exists (or if a file of the same name exists), tries to create a directory with the same name suffixed by 0, then 1, then ...

<?php

function createIncrementalDir($dir){
  $returnDir = "";
  if (! file_exists($dir)) {
    mkdir($dir);
    $returnDir = $dir;
  } else {
    if (! is_dir($dir)) {
      $dirok = 0;
      $i = 0;
      $newDir = "";
      while ($dirok == 0) {
        $newDir = $dir . $i;
        if (file_exists($newDir)) {
          if (is_dir($newDir)) {
            $dirok = 1;
            $returnDir = $newDir;
          }
          $i++;
        } else {
          mkdir($newDir);
          $returnDir = $newDir;
        }
      }
    } else {
      $returnDir = $dir;
    }
  }
  return $returnDir;
}

?>