I came across an interesting question on StackOverflow. Unfortunately the question was closed before I could answer. I’d like to answer it.
Can I convert
uniqid()to a timestamp?
From the PHP documentation on
without being passed any additional parameters the return value is little different from
The comments noted that
uniqid() outputs a hexadecimal string. The following script compares
uniqid() to the output of
microtime() converted to a hexadecimal string.
1 2 3 4 5 6 7
Immediately we see both have the same prefix. So what are the remaining characters of
Turns out the answer is pretty obvious. It’s the microseconds. But
uniqid() does not simply multiply
$microtome by 1,000,000. Instead it appends the microseconds as a hexidecimal string.
Another quick script as proof:
1 2 3 4 5 6 7 8 9
Pretty close. The few nanosecond difference is literally the runtime between executing line 1 and 2.
microtime() we’ve proven
uniqid(), without parameters, is the concatenation of a timestamp and microseconds as hexadecimal strings.
Why then did I say sort of?
The suffix. If you run the last script enough you’ll notice an inconsistency for low microsecond values.
Notice the missing zeroes. Given this inconsistency, can we trust the suffix is a specific number of hexadecimal characters (i.e. 5)?
The documentation states, without parameters,
uniqid() returns 13 characters. That said, the simplest code to get the timestamp from
uniqid() is to extract the prefix:
1 2 3
Why the negative anchor? Consider the Unix timestamp
4294967296. You don’t want to start Y2.1K!
After this exercise I reviewed the source code for
uniqid() to confirm this code is indeed safe.
So yes, you can convert
uniqid() to a timestamp.