How to avoid collision of upload file names

3

I'm making a site for uploading images, but when I upload two files with equal names, what I had before adds to the files directory .

This is the code I use for upload :

if(empty($_FILES)){
echo "<center><h1>Please, select the files</h1></center>";
}else{
    foreach($_FILES['file']['name'] as $key => $name){
        $_FILES['file']['size'][$key];
        if($_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'][$key],"files/{$_FILES['file']['name'][$key]}")){     
            $link = "files/" . $_FILES['file']['name'][$key];
            $name = $_FILES['file']['name'][$key];
            $uploaded[] = $name;
            ?>

            <?php
            }
        }
    }

The name the file is in the folder is defined by the line {$_FILES['file']['name'][$key]}

How to make the name of the file in the folder be its encrypted name, to avoid the error I mentioned above?

    
asked by anonymous 27.07.2015 / 05:14

1 answer

2

You can solve your problem in a very simple way, just add a numerical sequence if the file already exists:

if (empty($_FILES)) {
  echo "<center><h1>Please, select the files</center>";
} else {
   $number_add = 0;
    foreach ($_FILES['file']['name'] as $key => $name) {
        $_FILES['file']['size'][$key];
        if ($_FILES['file']['error'][$key] == 0) { 
            if (!file_exists("files/" . $_FILES['file']['name'][$key])) {
               $link = "files/" . $_FILES['file']['name'][$key];
               $name = $_FILES['file']['name'][$key];
            } else {
               $link = "files/" . $number_add .'_'. $_FILES['file']['name'][$key];
               $name = $number_add .'_'. $_FILES['file']['name'][$key];
               $number_add++;
            }
            move_uploaded_file($_FILES['file']['tmp_name'][$key], $link);
            $uploaded[] = $name;
        }
    }
}
    
27.07.2015 / 15:44