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.
That there, well explained :)
– Rafael Augusto