Is a timestamp in microseconds always unique?

前端 未结 2 570
失恋的感觉
失恋的感觉 2020-12-11 16:07

uniqid() in PHP generates a unique ID based on the current timestamp in microseconds. Is that really a foolproof way to generate a unique ID?

Even assuming there\'s

2条回答
  •  心在旅途
    2020-12-11 17:11

    Ask yourself why you need uniqid in the first place. For instance, I use uniquid as the filename of uploads to my website. There can be any number of users who upload at the same time so what I am concerned with is two or more files having the same id, BUT I know that a single user can only upload one file at a time. So, I prepend the username in front and will always have uniqueness.

    echo uniqid('username-'); // username-5621e3335ac0c
    

    Of course, you should always ask yourself if you need to use uniquid in the first place. If you know the reason you are creating the id can only happen every x seconds, minutes, etc then you can create an id the same way just use time :

    echo 'username-'.time(); // username-1445062025
    

提交回复
热议问题