PHP mkdir folders with the same name

Asked

Viewed 276 times

0

How to 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);

2 answers

2


Just as Rafael quoted in his reply, you just have to always check the existence of the directory before creating it. Assuming there are numerous directories with the same name, we can create a contactor that will be incremented until we find a valid value in which 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, supposing that $_POST["f_registro"] be it pasta, PHP will check if there is a directory pasta 04-09-2017. If it exists, it will check whether pasta 04-09-2017 (001) exists, after pasta 04-09-2017 (002), pasta 04-09-2017 (003), so on, until you find a name that is not an existing directory, creating it.

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

  • 1

    That there, well explained :)

1

You can check if the directory already exists, if it exists, I put 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
}
  • But what if it’s more than two folders with the same name?

  • 1

    @Henriquebretone Voce adds something else to the folder name, e.g.: pasta_1, pasta_2 and so on

Browser other questions tagged

You are not signed in. Login or sign up in order to post.