prevent file upload if it already exists using class class.upload.php from verot.net

1

This fragment is the one that is used to make the action of the form, but I would like to know how to do to check if the same file already exists, that you get a warning that there is already a file with the same name.

$handle = new upload($_FILES['image_field']);
if ($handle->uploaded) {
  $handle->file_new_name_body   = 'image_resized';
  $handle->image_resize         = true;
  $handle->image_x              = 100;
  $handle->image_ratio_y        = true;
  $handle->process('/home/user/files/');
  if ($handle->processed) {
    echo 'image resized';
    $handle->clean();
  } else {
    echo 'error : ' . $handle->error;
  }
}
    
asked by system_web 23.04.2018 в 18:53
source

1 answer

1

I can think of something like that to validate if the file exists in a directory with php.

$nombreArchivoSubido= 'aqui va el nombre del archivo que subiste';
$carpeta = '/nombreCarpetaARecorrer';
//usamos scandir para ver todo el contenido del archivo
$ficheros= scandir($carpeta);
//variable que incrementaremos si hay una coincidencia
$coincidencia= 0;
$mensaje = "";
//recorremos los archivos con for y condicionamos dentro con if
for($i=0;$i<=sizeof($ficheros);$i++){
//preguntamos si es igual al nombre del archivo
 if($nombreArchivoSubido == $ficheros[$i]){
    //incrementamos la variable coincidencia
    $coincidencia++;
  }

}

//preguntamos si la variable coincidencia es mayor a 0
if($coincidencia>0){

  $mensaje = "Este archivo existe! ¯\_(ツ)_/¯ "

}
return $mensaje;

In the code I did above, comment on what you are doing, but what is important is the scandir ,

What does scandir do?

  

Well its functionality is to list the files located inside and what   returns as an array.

I hope you serve.Greetings!.

    
answered by 23.04.2018 / 19:12
source