Is the timestamp in microseconds always unique?

uniqid () in PHP generates a unique identifier based on the current timestamp in microseconds. Is this a really reliable way to create a unique identifier?

Even assuming that a single user running a single script with a loop generating a timestamp in microseconds, can there really be a theoretical guarantee that it is not equal? And in practice, the likelihood that the probability is completely negligible?

For clarity, let's say your loop is none other than this:

foreach($things as $thing){ var_dump(microtime()); } 

Is there any theoretical chance that it cannot be unique, and if so, how realistic is this in practice?

+5
source share
2 answers

Microsecond identifiers are only guaranteed within limits. Single-threaded scripts on a single computer are probably quite safe in this regard. However, as soon as you start talking about parallel execution, whether on multiple processors on the same computer or especially on multiple computers, all bets are disabled.

So it depends on what you want to use this identifier for. If you just use it to generate an identifier that is used only within the same script, it is probably quite safe. For instance:

 <?php $randomId = uniqid(); ?> <div id="<?php echo $randomId; ?>"></div> <script> var div = document.getElementById('<?php echo $randomId; ?>'); ... </script> 

You probably won't encounter any problems with this limited use.

However, if you start generating file names using uniqid or other similar applications that are used in conjunction with other external scripts, I would not rely on it. For file names, using a hash based on the contents of the file may be a good idea. For universal decentralized randomly generated identifiers, UUIDs are a good fit (because they were designed for this purpose).

+6
source

Ask yourself why you need uniqid in the first place. For example, I use uniquid as the file name of the downloads to my site. There can be any number of users that are downloading at the same time, so I mean two or more files with the same identifier, BUT I know that one user can only upload one file at a time. So, I precede the username in front and will always be unique.

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

Of course, you should always ask yourself if you need to use non-fluid in the first place. If you know the reason why you are creating an identifier, this can happen only every x seconds, minutes, etc. Then you can create an identifier in the same way as using time:

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

Source: https://habr.com/ru/post/1206702/


All Articles