Upload image with unique name

后端 未结 2 339
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.

提交回复
热议问题