Link to home
Start Free TrialLog in
Avatar of danzzz
danzzz

asked on

Creating a unique number from a time stamp PHP

Hi,

What would be the best PHP function to use in order to create a unique reference up to 20 characters based on a time stamp.

thanks in advance,
Dan
Avatar of marklogan
marklogan
Flag of United Kingdom of Great Britain and Northern Ireland image

Does it have to be 20, can it not be 32 characters long?

As you could create the md5 hash of a timestamp, should be unique unless two get generated at exactly the same time.
The function time() "Returns the current time measured in the number of seconds since the Unix Epoch (January 1 1970 00:00:00 GMT).", aka a large integer of 10 places. How precise do you need it? This one obviously won't work if you need finely granularity than seconds on the unique ids.... but it works just fine in situations like I use it: measure temperatures every two minutes.
ASKER CERTIFIED SOLUTION
Avatar of marklogan
marklogan
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
As far as I can tell, you need two pieces, a random bit and the timestamp, if you want it to be based on timestamp + unique with finer than second granularity.

Akin to the unix command date '+%s%N', using a timestamp + a random number should do the trick:

srand ((double) microtime( )*10000000000);
$random_number = rand( );
$uniqueID = time().$random_number;

// or the lazy way:
$uniqueID = exec("date '+%s%N'");

Open in new window

Avatar of Julian Hansen
You can try uniqueid() (value of true extends the length

http://www.php.net/manual/en/function.uniqid.php

To get to 20 chars you can take the least significant 20 bytes.


*microtime( )*10000000000 should be microtime( )*1000000. Too many 0s.....

If you want alpha-numeric characters, uniqid will work.
Avatar of danzzz
danzzz

ASKER

Thanks for all the answers.

Solution by marklogan did the job perfectly since it turns out the length has to be exactly 20 characters.

Many thanks,
Dan