Unique key generation

后端 未结 13 2188
一个人的身影
一个人的身影 2020-12-03 05:53

I looking for a way, specifically in PHP that I will be guaranteed to always get a unique key.

I have done the following:

strtolower(substr(crypt(tim         


        
相关标签:
13条回答
  • 2020-12-03 06:08

    I'm still not seeing why the passwords have to be unique? What's the downside if 2 of your users have the same password?

    This is assuming we're talking about passwords that are tied to userids, and not just unique identifiers. If that's what you're looking for, why not use GUIDs?

    0 讨论(0)
  • 2020-12-03 06:13

    Without writing the code, my logic would be:

    Generate a random string from whatever acceptable characters you like.
    Then add half the date stamp (partial seconds and all) to the front and the other half to the end (or somewhere in the middle if you prefer).

    Stay JOLLY!
    H

    0 讨论(0)
  • 2020-12-03 06:13

    I usually do a random substring (randomize how many chars between 8 an 32, or less for user convenience) or the MD5 of some value I have gotten in, or the time, or some combination. For more randomness I do MD5 of come value (say last name) concatenate that with the time, MD5 it again, then take the random substring. Yes, you could get equal passwords, but its not very likely at all.

    0 讨论(0)
  • 2020-12-03 06:14

    I recently wanted a quick and simple random unique key so I did the following:

    $ukey = dechex(time()) . crypt( time() . md5(microtime() + mt_rand(0, 100000)) ); 
    

    So, basically, I get the unix time in seconds and add a random md5 string generated from time + random number. It's not the best, but for low frequency requests it is pretty good. It's fast and works.

    I did a test where I'd generate thousands of keys and then look for repeats, and having about 800 keys per second there were no repetitions, so not bad. I guess it totally depends on mt_rand()

    I use it for a survey tracker where we get a submission rate of about 1000 surveys per minute... so for now (crosses fingers) there are no duplicates. Of course, the rate is not constant (we get the submissions at certain times of the day) so this is not fail proof nor the best solution... the tip is using an incremental value as part of the key (in my case, I used time(), but could be better).

    0 讨论(0)
  • 2020-12-03 06:15

    If you use your original method, but add the username or emailaddress in front of the password, it will always be unique if each user only can have 1 password.

    0 讨论(0)
  • 2020-12-03 06:17

    Any algorithm will result in duplicates.

    Therefore, might I suggest that you use your existing algorithm* and simply check for duplicates?

    *Slight addition: If uniqid() can be non-unique based on time, also include a global counter that you increment after every invocation. That way something is different even in the same microsecond.

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