5

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
  • 2,198
  • 9
  • 29
  • 40

3 Answers3

8

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();
amitchhajer
  • 12,492
  • 6
  • 40
  • 53
3

You can use a combination of uniqid() and time() like so:

$s = uniqid(time(), true);

Example output:

1346136883503c6b3330caf5.19553126
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • We can also complexify the generation of a unique id with the function md5 `md5(uniqid(time(), true))`. – Breith Mar 01 '17 at 09:16
1

Is this what you're looking for? uniqid()

From the doc:

Gets a prefixed unique identifier based on the current time in microseconds.

Lucas Green
  • 3,951
  • 22
  • 27
  • will 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 – user1518659 Aug 28 '12 at 06:36
  • You'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. – Álvaro González Aug 28 '12 at 06:46
  • http://php.net/manual/en/function.uniqid.php the doc indicates that you can provide a prefix and an entropy source. – Lucas Green Aug 28 '12 at 06:48
  • what do they mean by prefix string? I dont get it.. entropy too.. @Mythril – user1518659 Aug 28 '12 at 06:51
  • A 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. – Lucas Green Aug 28 '12 at 06:53
  • have you tried 'time().'-'.mt_rand();'.. can you ensure uniqid() gives a better result than this? i mean what is the best way.. no offence. – user1518659 Aug 28 '12 at 06:55
  • do you want to store Id's in sorted order? – amitchhajer Aug 28 '12 at 06:59