search
HomeBackend DevelopmentPHP Tutorialphp automatically generates unique ids

php automatically generates unique ids

Sep 12, 2019 pm 05:43 PM
idphpAutomatic generated

php automatically generates unique ids

PHP uniqid() function can be used to generate a unique identifier that is not repeated, which is based on the current timestamp in microseconds. In cases of high concurrency or extremely 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.

Description

##string uniqid ([ string $prefix = "" [, bool $more_entropy = false ]] )

Get a prefixed unique ID based on the current time microseconds.

Parameters

prefix

Useful parameters. For example: if on multiple hosts a unique ID may be generated in the same microsecond.

If prefix is ​​empty, the length of the returned string is 13. If more_entropy is TRUE, the length of the returned string is 23.

more_entropy

If set to TRUE, uniqid() will add extra entropy to the end of the returned string (using a combined linear congruential generator). Make the unique ID more unique.

PHP uniqid() Method 1 to generate non-duplicate unique identifiersThis method will generate a large amount of duplicate data. Running the following PHP code will result in the array index being the unique identifier generated, corresponding to The element value of 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 &#39;<pre class="brush:php;toolbar:false">&#39;;        
print_r($duplicates);        
echo &#39;
'; ?>

PHP uniqid() Method 2 for generating non-duplicate unique identifiersThe amount of duplicate unique identifiers generated by this method is significantly reduced.

<?php        
$units = array();        
for($i=0;$i<1000000;$i++){                
$units[] = uniqid(&#39;&#39;,true);        
}        
$values  = array_count_values($units);       
$duplicates = [];        
foreach($values as $k=>$v){                
if($v>1){                        
$duplicates[$k]=$v;                
}        
}        
echo &#39;<pre class="brush:php;toolbar:false">&#39;;        
print_r($duplicates);        
echo &#39;
'; ?>

PHP uniqid() Generate unique identifier method threeThere 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 &#39;<pre class="brush:php;toolbar:false">&#39;;        
print_r($duplicates);        
echo &#39;
'; ?>

PHP uniqid() generates unique identifier method fourUse the session_create_id() function to generate a unique identifier. After actual testing, it was found that even if session_create_id() is called cyclically, 100 million times, there was no duplication.
php session_create_id() is a new function in PHP 7.1. It is used to generate session id. It cannot be used in lower versions.

The above content is for reference only!

Recommended video tutorial:

PHP video tutorial

The above is the detailed content of php automatically generates unique ids. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:博客园. If there is any infringement, please contact admin@php.cn delete
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor