1

I would like to create a unique id in php.I used uniqid() but microtime is not helping because the function is inside a loop and a set of consecutive results are exactly the same!! So i am wondering if i can use nano time.In linux it possible using system() function. Is there any such ways in windows through which I can get nano time in PHP?

Nidhin David
  • 2,426
  • 3
  • 31
  • 45
  • did u consider a usleep(1) in your loop. – j_mcnally Apr 11 '14 at 02:53
  • 1
    http://codepad.viper-7.com/6zd3WB no duplicates how about `md5(uniqid(rand(), true));` –  Apr 11 '14 at 02:55
  • Sorry if it was duplicate.I only searched for nanotime. – Nidhin David Apr 11 '14 at 03:02
  • Thanks @Dagon md5 worked.no identical string in 5000 values.Thats enough for me. – Nidhin David Apr 11 '14 at 03:12
  • Thanks @j_mcnally for telling me about usleep().Its something i always needed to replace sleep.But usleep(1) can never generate a unique string inside small loops.Even with uniqid(2000) i got minimum of 5 identical results.But md5(uniqid(rand(), true)); worked – Nidhin David Apr 11 '14 at 03:14
  • its not the md5, that's just a wrapper, to make them pretty, its the rand() prefix that is stopping the duplication –  Apr 11 '14 at 03:15
  • 1
    sweet glad it works, seeding uniqid with rnd better entropy than just time, seems like a good idea. – j_mcnally Apr 11 '14 at 03:16
  • perhaps even uniqid("", true) would work too, i think the key here is "moreEntropy" i could be wrong tho. – j_mcnally Apr 11 '14 at 03:17
  • @Dagon Yeha I got it.It worked.Very nice idea...I forgot aboun rand().It works like a charm. – Nidhin David Apr 11 '14 at 05:17

1 Answers1

2

my idea is to add rand() as a prefix like so:

md5(uniqid(rand(), true));

the md5() is just a wrapper to make them pretty, you can remove it or format the results in other way depending on your need.

  • 1
    md5 is probably bad in this instance, there is a posibility of a hash collision, which uniqid doesn't have because it uses time for entropy. `uniqid('', true)` or `uniqid(rand(), true)` is probably the safest. Although the prefix is not required but adds to the overall entropy of the generated id. – j_mcnally Apr 11 '14 at 03:23