Create Unique Image Names

前端 未结 15 2106
暗喜
暗喜 2021-01-06 08:02

What\'s a good way to create a unique name for an image that my user is uploading?

I don\'t want to have any duplicates so something like MD5($filename) isn\'t suita

相关标签:
15条回答
  • 2021-01-06 08:34

    I think it would be good for you.

    <?php
        $name=uniqid(mt_rand()).$image_name;
     ?>
    
    0 讨论(0)
  • 2021-01-06 08:38

    You should try to meet two goals: Uniqueness, and usefulness.

    Using a GUID guarantees uniqueness, but one day the files may become detached from their original source, and then you will be in trouble.

    My typical solution is to embed crucial information into the filename, such as the userID (if it belongs to a user) or the date and time uploaded (if this is significant), or the filename used when uploading it.

    This may really save your skin one day, when the information embedded in the filename allows you to, for example, recover from a bug, or the accidental deletion of records. If all you have is GUIDs, and you lose the catalogue, you will have a heck of a job cleaning that up.

    For example, if a file "My Holiday: Florida 23.jpg" is uploaded, by userID 98765, on 2013/04/04 at 12:51:23 I would name it something like this, adding a random string ad8a7dsf9:

    20130404125123-ad8a7dsf9-98765-my-holiday-florida-23.jpg

    Uniqueness is ensured by the date and time, and random string (provided it is properly random from /dev/urandom or CryptGenRandom. If the file is ever detached, you can identify the user, the date and time, and the title. Everything is folded to lower case and anything non-alphanumeric is removed and replaced by dashes, which makes the filename easy to handle using simple tools (e.g. no spaces which can confuse badly written scripts, no colons or other characters which are forbidden on some filesystems, and so on).

    0 讨论(0)
  • 2021-01-06 08:41

    try this file format:

    $filename = microtime(true) . $username . '.jpg';
    
    0 讨论(0)
提交回复
热议问题