How to avoid collision of upload file names

Asked

Viewed 395 times

4

I’m making a website for upload of images, only, when I do the upload of two files with equal names, what there was before some of the file 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 file name in the folder your encrypted name, to avoid the error I mentioned above?

  • What do you mean by "your encrypted name"? I mean, are you assuming that there is an encrypted name for the file? Where would it have been created?

  • No, I want the file name in the folder to be an original encrypted file name

  • 1

    Sorry, I really don’t understand. Well, md5, sha1 and crypt are unidirectional encryption PHP functions, only if you are going to encrypt the file name, for equal names, it has equal results, unless you add a variable part in the name, for example the date/time, only this by itself will make the name different. And there is more: although the chance is really small, there is no guarantee that the result of an encryption will not repeat itself with other data.

1 answer

3


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;
        }
    }
}
  • Exactly that, solved the problem. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.