Upload image with unique name

后端 未结 2 340
Happy的楠姐
Happy的楠姐 2021-01-16 03:55

So I am trying to upload some images to a folder on my server with the script below,but it saves every image as \"image.jpg\" and it overwrites the last uploaded image if I

相关标签:
2条回答
  • 2021-01-16 04:27

    You can implement something like Windows's auto-file-renaming:

    $try = 1;
    while($file_exists($target_file)) {
        $target_file = preg_replace('/(\(\\d+\))*(\.[^\\(\\)]+)$/',
            "({$try})\\2", $target_file);
        $try++;
    }
    

    This will replace the file "duplicate.jpg" with "duplicate(1).jpg", then "duplicate(2).jpg", and so on.

    It will still be prone to unlikely race conditions, just as using uniqid() or microtime() (which, conflict-wise, are both better).

    Otherwise, always use tempnam(). You can check out this answer.

    0 讨论(0)
  • 2021-01-16 04:46

    A simple way to get a unique filename is to get the current Unix time in milliseconds and append (or prepend) that to the filename. The command to use is microtime().

    For example:

    $target_file = $target_dir . microtime() . basename($_FILES["fileToUpload"]["name"]);
    

    You could also try things like hashing the file to get a unique hash with low probability of collisions, but this is faster and just as effective.

    0 讨论(0)
提交回复
热议问题