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
danzzzAsked:
Who is Participating?
 
markloganCommented:
You would have to check both are unique though, if two are generated at the same time, they will be the same.

Could you not store a new record in the database each time and take the primary key, they would ensure they are always unique?
$hash = md5(time());

// Would generate 32 char hash.

$hash = time().time();

// Would generate 20.

Open in new window

0
 
markloganCommented:
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.
0
 
hawardenCommented:
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.
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
hawardenCommented:
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

0
 
Julian HansenCommented:
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.


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

If you want alpha-numeric characters, uniqid will work.
0
 
danzzzAuthor Commented:
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
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.