PHP implementation of K-Sortable Unique Identifiers (KSUID).
Cross-compatible with:
- owpz/ksuid (TypeScript)
- owpz/ksuid-rs (Rust)
- segmentio/ksuid (Go — the original reference)
All implementations produce identical output for the same input: same base62 encoding, same binary format, same epoch, and same sorting order.
- PHP 8.2+
- ext-gmp
composer require owpz/ksuid-phpuse Owpz\Ksuid\Ksuid;
$ksuid = Ksuid::generate();
echo $ksuid; // e.g. "2QnM2STpxF0wgOjCAHZ4LUZXF5m"
echo $ksuid->toString(); // same as (string) $ksuid$parsed = Ksuid::parse('0o5sKzFDBc56T8mbUP8wH1KpSX7');
echo $parsed->getTimestamp(); // Unix timestamp
echo $parsed->getTimestampOffset(); // Seconds since KSUID epoch
echo $parsed->getDate()->format('Y-m-d H:i:s');
$payload = $parsed->getPayload(); // 16-byte binary string
$bytes = $parsed->getBytes(); // 20-byte binary string$ksuid = Ksuid::parseOrNull('maybe-invalid');
if ($ksuid === null) {
// Handle invalid input
}
$ksuid = Ksuid::fromBytesOrNull($rawBytes);$nil = Ksuid::nil();
echo $nil; // "000000000000000000000000000"
echo $nil->isNil(); // true$a = Ksuid::generate();
$b = Ksuid::generate();
$a->compare($b); // -1, 0, or 1
$a->equals($b); // bool
// Sort an array of KSUIDs
usort($ksuids, fn(Ksuid $a, Ksuid $b) => $a->compare($b));$ksuid = Ksuid::generate();
$next = $ksuid->next(); // Increment payload by 1
$prev = $ksuid->prev(); // Decrement payload by 1
// Handles overflow/underflow: payload wraps and timestamp adjusts// From Unix timestamp + payload
$ksuid = Ksuid::fromParts(time(), random_bytes(16));
// From timestamp offset (seconds since KSUID epoch) + payload
// This matches the Go/TypeScript API
$ksuid = Ksuid::fromTimestampOffset(95004740, $payload);
// From raw 20-byte binary
$ksuid = Ksuid::fromBytes($raw20bytes);A KSUID is a 20-byte value:
| Bytes | Description |
|---|---|
| 0–3 | Big-endian uint32 timestamp (seconds since KSUID epoch 2014-05-13T16:53:20Z) |
| 4–19 | Cryptographically random payload |
Encoded as a 27-character base62 string (0-9A-Za-z), zero-padded for fixed width.
KSUIDs are lexicographically sortable by creation time — string comparison (strcmp) produces chronological order.
This library uses the same constants, base62 alphabet, binary layout, and encoding algorithm as the Go, TypeScript, and Rust implementations. KSUIDs generated by any implementation can be parsed by any other.
Test vectors from the Go reference implementation are included in the test suite to guarantee compatibility.
composer install
vendor/bin/phpunit