PHP mkdir folders with the same name

0

How do you do when creating a directory with mkdir it does not replace if there is one with the same name, keep the two folders with the same name or with some auto-increment to number the folders?

 $vregistro = utf8_decode($_POST['f_registro']);

 $d = date(' d-m-Y'); 
mkdir("C:\local\Arquivos\Documentos&Logos/$vregistro" . $d, 0777, true);
    
asked by anonymous 04.09.2017 / 16:58

2 answers

2

As Rafael quoted in his reply, you just need to check the directory's existence before you create it. Assuming there are many directories with the same name, we can create a contactor that will be incremented until we find a valid value where the directory does not exist.

$vregistro = utf8_decode($_POST['f_registro']);
$d = date(' d-m-Y'); 

$name = $vregistro . $d;

// Verifica se o diretório original existe:
if (file_exists($name)) {
    // Existe, então cria o contador:
    $i = 1;

    // Executa enquanto o diretório existir:
    while (file_exists(sprintf("%s (%03d)", $name, $i))) {
        $i++;
    }

    // Encontrou um diretório que não existe, então define o novo nome:
    $name = sprintf("%s (%03d)", $name, $i);
}

// Cria o diretório:
mkdir($name, 0777, true);

So, assuming that $_POST["f_registro"] is pasta , PHP will check for the pasta 04-09-2017 directory. If it exists, it will check whether pasta 04-09-2017 (001) exists, then pasta 04-09-2017 (002) , pasta 04-09-2017 (003) , and so on, until it finds a name other than an existing directory by creating it.

  

Notice that instead of putting the counter displaying as 1, 2, 3, ..., I put displaying as 001, 002, 003, etc; this is because if you got to create the directory 10, or higher, the order of the directories would be affected, because the operating system alphabetically by the name, displaying the 10 before the 2, for example. Adding the leading zeros will not occur unless the numbering exceeds 1000.

    
04.09.2017 / 18:14
1

You can check if the directory already exists, if it exists, you place an additional one in the new name.

if(file_exists($vregistro)){
   // Aqui voce cria pasta com o nome atual e algo a mais 
}else{
  // Aqui voce apenas cria com o nome atual
}
    
04.09.2017 / 17:03