how to generate unique id in php based on current data and time?
25,514
Solution 1
Using time() to create sortable unique id's
Concatenating strings will also further randomize your desired result and still keep it sortable. manual here
$uniqueId= time().'-'.mt_rand();
Solution 2
You can use a combination of uniqid()
and time()
like so:
$s = uniqid(time(), true);
Example output:
1346136883503c6b3330caf5.19553126
Solution 3
Is this what you're looking for? uniqid()
From the doc:
Gets a prefixed unique identifier based on the current time in microseconds.
Author by
user1518659
Updated on July 08, 2020Comments
-
user1518659 almost 4 years
I need to generate a unique ID in php based on current date and time to keep a log of when i am running code. i.e. every time i run the code it should be able to generate a unique id based on current date and time.
Hope I am clear with my ques. How to do that?
-
user1518659 over 11 yearswill it generate uniqueid() based on time only?? if so what happens if there is a time conflict...i am not clear.. i need a manual code that generates unique id every time i run the code @Mythril
-
Álvaro González over 11 yearsYou'll possibly get the same ID if your IDs are generated on the same microsecond. It's difficult but could happen. You can make it harder by appending a random string--the base technique is good IMHO.
-
Lucas Green over 11 yearsphp.net/manual/en/function.uniqid.php the doc indicates that you can provide a prefix and an entropy source.
-
user1518659 over 11 yearswhat do they mean by prefix string? I dont get it.. entropy too.. @Mythril
-
Lucas Green over 11 yearsA prefix is an arbitrary string that you provide to give the id extra meaning/differentiate it (it's up to you really). An entropy source is just an additional number (preferably random or pseudo-random) that will make the id less likely to collide with previously generated ids.
-
user1518659 over 11 yearshave you tried 'time().'-'.mt_rand();'.. can you ensure uniqid() gives a better result than this? i mean what is the best way.. no offence.
-
amitchhajer over 11 yearsdo you want to store Id's in sorted order?
-
Breith about 7 yearsWe can also complexify the generation of a unique id with the function md5
md5(uniqid(time(), true))
.