Reputation: 2246
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?
Upvotes: 5
Views: 33076
Reputation: 173642
With PHP 7 you can use this to generate a sufficiently random value based on the current timestamp:
$s = time() . bin2hex(random_bytes(10));
Do note that after 265 years (starting with 11 digits in 2286) the timestamp would get another digit, and sorting order will be off; if your code is expected to survive for that long, you may want to consider some padding.
You can use a combination of uniqid()
and time()
like so:
$s = uniqid(time(), true);
Example output:
1346136883503c6b3330caf5.19553126
Upvotes: 4
Reputation: 12840
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();
Upvotes: 8
Reputation: 3959
Is this what you're looking for? uniqid()
From the doc:
Gets a prefixed unique identifier based on the current time in microseconds.
Upvotes: 1