I am trying to move a file from php but without replacing it if it already exists.
The fact is that I'm not sure how to do it if there is more than one.
The code I'm using is this:
$extension = explode(".", $_GET["foto"]);
if (file_exists("../../Nuevas/".$Resultados['codigo'].".CR2")) { $nombrenuevo=$Resultados['codigo']."-1.CR2" } else { $nombrenuevo=$Resultados['codigo'].".CR2"; }
if (rename ("../Fotos/cr2/".$extension[0].".CR2", "../../Nuevas/".$nombrenuevo)) {
if (!unlink("../Fotos/jpg/".$_GET["foto"])) { $error = "Error Borrando ".$_GET["foto"]; }
$ok = "el nombre del fichero ha sido cambiado\n";
} else {
$error = "Se ha producido un error al intentar cambiar el nombre\n";
}
But in the case that there are more than two files with the same name, the second one is replaced. Is there any way to see if there is more than one?
Thank you very much for your help.
Possible solution that I have applied.
$extension = explode(".", $_GET["foto"]);
$nombrenuevo=$Resultados['codigo'].".CR2";
if (file_exists("../../Nuevas/".$nombrenuevo)) {
for ($i=1; ; $i++){
if (!file_exists("../../Nuevas/".$Resultados['codigo']."-".$i.".CR2")) { $nombrenuevo=$Resultados['codigo']."-".$i.".CR2"; break; }
}
if (rename ("../Fotos/cr2/".$extension[0].".CR2", "../../Nuevas/".$nombrenuevo)) {
if (!unlink("../Fotos/jpg/".$_GET["foto"])) { $error = "Error Borrando ".$_GET["foto"]; http_response_code(500); }
$ok = "el nombre del fichero ha sido cambiado\n";
} else {
$error = "Se ha producido un error al intentar cambiar el nombre\n"; http_response_code(500);
}
At the moment I can not test if it works since I have a syntax error and I'm looking for the bug.