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.