What is a PHP uniqid()?
The uniqid() function in PHP generates a unique identifier based on the current time in microseconds. Unlike UUIDs (Universal Unique Identifiers), which are generated securely and randomly, a standard PHP uniqid is strictly tied to the exact server time when the function was executed.
How does the uniqid to timestamp conversion work?
A standard PHP uniqid (without any custom prefixes) consists of 13 hexadecimal characters. The secret to decoding it lies in the first 8 characters. These represent the exact Unix Timestamp (in seconds) converted into hexadecimal format. The remaining 5 characters represent the microseconds.
By extracting these first 8 characters and converting them from base-16 (hexadecimal) to base-10 (decimal), you extract the exact Unix epoch timestamp. Once you have the Unix timestamp, it can be easily converted into UTC or your local timezone.
This decoder accepts standard IDs as well as IDs with a prefix, such as order-65f012ab34c5d. It uses the first eight hexadecimal characters of the identifier itself, so a prefix does not change the decoded timestamp.
When to use a uniqid decoder
Decoding a uniqid can help investigate logs, trace when a record was created, or compare identifiers generated by different systems. The time is useful context, but it should not be treated as proof of the exact application event because server clocks and processing delays can differ.
How to decode uniqid in PHP
If you want to decode a uniqid directly in your backend PHP application, you can use the following snippet:
<?php
$id = "65f012ab34c5d";
// Extract the first 8 characters
$hexTime = substr($id, 0, 8);
// Convert from hexadecimal to decimal
$timestamp = hexdec($hexTime);
// Print the formatted date
echo date('Y-m-d H:i:s', $timestamp);
?>