The PHP uniqid() function can be used to generate non-repetitive unique identifiers based on the current timestamp of microseconds. In the case of high concurrency or very short intervals (such as loop code), a large amount of duplicate data will appear. Even if the second parameter is used, it will be repeated. The best solution is to combine the md5 function to generate a unique ID.
Method 1
This method will generate a large amount of duplicate data. Run the following PHP code and the array index is the unique identifier generated, and the corresponding element value is the number of times the unique identifier is repeated.
<?php $units = array(); for($i=0;$i<1000000;$i++){ $units[] = uniqid(); } $values = array_count_values($units); $duplicates = []; foreach($values as $k=>$v){ if($v>1){ $duplicates[$k]=$v; } } echo '<pre>'; print_r($duplicates); echo '</pre>'; ?>
Method 2
This method generates a significantly reduced number of unique identifier duplications.
<?php $units = array(); for($i=0;$i<1000000;$i++){ $units[] = uniqid('',true); } $values = array_count_values($units); $duplicates = []; foreach($values as $k=>$v){ if($v>1){ $duplicates[$k]=$v; } } echo '<pre>'; print_r($duplicates); echo '</pre>'; ?>
Method 3
There is no duplication in the unique identifier generated by this method.
<?php $units = array(); for($i=0;$i<1000000;$i++){ $units[]=md5(uniqid(md5(microtime(true)),true)); } $values = array_count_values($units); $duplicates = []; foreach($values as $k=>$v){ if($v>1){ $duplicates[$k]=$v; } } echo '<pre>'; print_r($duplicates); echo '</pre>'; ?>
Method 4
Use the session_create_id() function to generate a unique identifier. After actual testing, it was found that even if session_create_id() is called 100 million times in a loop, there was no duplication. php session_create_id() is a new function added in php 7.1, used to generate session id, and the lower version cannot be used.
The above is the detailed content of the high-concurrency php uniqid does not repeat the unique identifier generation scheme. For more information about high-concurrency php uniqid unique identifiers, please follow my other related articles!