Unique key generation

后端 未结 13 2200
一个人的身影
一个人的身影 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: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).

提交回复
热议问题