Documentation

Uuid
in package
implements Stringable

Generates, compresses, and expands Universally Unique Identifiers.

This class can generate UUIDs of versions 1 through 7.

It is also possible to create a new instance of this class from a UUID string of any version via the Uuid::createFromString() method.

This class implements the \Stringable interface, so getting the canonical string representation of a UUID is as simple as casting an instance of this class to string.

Because the canonical string representation of a UUID requires 36 characters, e.g. 4e917aef-2843-5b3c-8bf5-a858ee6f36bc, which can be quite cumbersome, this class can also compress and expand UUIDs to and from more compact representations for storage and other uses. In particular:

  • The Uuid::getBinary() method returns the 128-bit (16 byte) raw binary representation of a UUID. This form maintains the same sort order as the full form and is the most space-efficient form possible.

  • The Uuid::getShortForm() method returns a customized base 64 or base 32 encoding of the binary form of the UUID. Both short forms maintain the same sort order as the full form and are URL safe. The base 64 form is 22 characters long. The base 32 form is 26 characters long, but contains only digits and lowercase letters, which may be useful in some situations.

For convenience, two static methods, Uuid::compress() and Uuid::expand(), are available in order to simplify the process of converting an existing UUID string between the full, short, or binary forms.

For the purposes of software applications that use relational databases, the most useful UUID versions are v7 and v5:

  • UUIDv7 is ideal for generating permanently stored database keys, because these UUIDs naturally sort according to their chronological order of creation. This is the default version when generating a new UUID.

  • UUIDv5 is ideal for situations where UUIDs need to be generated on demand from pre-existing data, but will not be stored permanently. The generation algorithm for UUIDv5 always produces the same output given the same input, so these UUIDs can be regenerated any number of times without varying.

The specification for UUIDv2 is DCE 1.1 Authentication and Security Services https://pubs.opengroup.org/onlinepubs/9696989899/chap5.htm#tagcjh_08_02_01_01

The specifications for all other UUID versions are defined in RFC 9562 https://www.rfc-editor.org/info/rfc9562

Table of Contents

Interfaces

Stringable

Constants

BASE32_ALT  = '0123456789abcdefghjkmnpqrstvwxyz'
BASE32_HEX  = '0123456789abcdefghijklmnopqrstuv'
Constants used to implement an alternative version of base32hex encoding for compressed UUID strings. Specifically, this uses "Crockford Base32" in order to avoid visually confusing characters.
BASE64_SORTABLE  = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~ '
BASE64_STANDARD  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
Constants used to implement an alternative version of base64 encoding for compressed UUID strings.
COMPRESS_BASE32  = 2
COMPRESS_BASE64  = 1
COMPRESS_BINARY  = 0
Constants used to select a short form type for the compress() method.
DEFAULT_VERSION  = 7
Default UUID version to create.
KNOWN_VERSIONS  = [0, 1, 2, 3, 4, 5, 6, 7, 8, 15]
UUID versions that this class will recognize as valid.
MAX_UUID  = 'ffffffff-ffff-ffff-ffff-ffffffffffff'
The special max UUID.
NAMESPACE_DNS  = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'
The predefined namespace UUID for fully qualified domain names.
NAMESPACE_OID  = '6ba7b812-9dad-11d1-80b4-00c04fd430c8'
The predefined namespace UUID for ISO Object Identifiers.
NAMESPACE_URL  = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'
The predefined namespace UUID for URLs.
NAMESPACE_X500  = '6ba7b814-9dad-11d1-80b4-00c04fd430c8'
The predefined namespace UUID for X.500 Distinguishing Names.
NIL_UUID  = '00000000-0000-0000-0000-000000000000'
The special nil UUID.
SUPPORTED_VERSIONS  = [0, 1, 2, 3, 4, 5, 6, 7, 15]
UUID versions that this class can generate.

Properties

$clock_seq  : array<string|int, mixed>
$namespace  : string
$node  : string
$prev_timestamps  : array<string|int, mixed>
$timestamp  : float
$utc  : object
$uuid  : string
$version  : int

Methods

__construct()  : mixed
Constructor.
__toString()  : string
Returns the string representation of the generated UUID.
compress()  : string
Convenience method to get the binary or short form of a UUID string.
create()  : Uuid
Creates a new instance of this class.
createFromString()  : Uuid
Creates an instance of this class from an existing UUID string.
expand()  : string
Convenience method to get the full form of a UUID string.
getBinary()  : string
Returns a binary representation of the UUID.
getNamespace()  : string
Returns the fully expanded value of self::$namespace.
getShortForm()  : string
Compresses $this->uuid to a 22- or 26-character string.
getVersion()  : int
Returns the version of this UUID.
setNamespace()  : void
Sets self::$namespace to the binary form of a UUID.
adjustTimestamp()  : int
Adjusts a Unix timestamp to meet the needs of the this UUID version.
decodeBase32Hex()  : string
Converts a base32hex string to hexadecimal.
encodeBase32Hex()  : string
Converts a hexadecimal string to base32hex.
getGregTimeParts()  : array<string|int, mixed>
Helper method for getHexV1 and getHexV6.
getHexV1()  : string
UUIDv1: Time-based (but not time-sortable) UUID version.
getHexV2()  : string
UUIDv2: DCE security version. Suitable only for specific purposes and is rarely used.
getHexV3()  : string
UUIDv3: Creates a UUID for a name within a namespace using an MD5 hash.
getHexV4()  : string
UUIDv4: Creates a UUID from random data.
getHexV5()  : string
UUIDv5: Creates a UUID for a name within a namespace using an SHA-1 hash.
getHexV6()  : string
UUIDv6: Time-sortable UUID version.
getHexV7()  : string
UUIDv7: Improved time-sortable UUID version.
setTimestamp()  : void
Sets $this->timestamp to a microsecond-precision Unix timestamp.

Constants

BASE32_ALT

public mixed BASE32_ALT = '0123456789abcdefghjkmnpqrstvwxyz'

BASE32_HEX

Constants used to implement an alternative version of base32hex encoding for compressed UUID strings. Specifically, this uses "Crockford Base32" in order to avoid visually confusing characters.

public mixed BASE32_HEX = '0123456789abcdefghijklmnopqrstuv'

BASE64_SORTABLE

public mixed BASE64_SORTABLE = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz~ '

BASE64_STANDARD

Constants used to implement an alternative version of base64 encoding for compressed UUID strings.

public mixed BASE64_STANDARD = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='

COMPRESS_BASE32

public mixed COMPRESS_BASE32 = 2

COMPRESS_BASE64

public mixed COMPRESS_BASE64 = 1

COMPRESS_BINARY

Constants used to select a short form type for the compress() method.

public mixed COMPRESS_BINARY = 0

DEFAULT_VERSION

Default UUID version to create.

public mixed DEFAULT_VERSION = 7

KNOWN_VERSIONS

UUID versions that this class will recognize as valid.

public mixed KNOWN_VERSIONS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 15]

Versions 0 and 15 refer to the special nil and max UUIDs. Version 8 is for "experimental or vender-specific use cases."

MAX_UUID

The special max UUID.

public mixed MAX_UUID = 'ffffffff-ffff-ffff-ffff-ffffffffffff'

NAMESPACE_DNS

The predefined namespace UUID for fully qualified domain names.

public mixed NAMESPACE_DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'

NAMESPACE_OID

The predefined namespace UUID for ISO Object Identifiers.

public mixed NAMESPACE_OID = '6ba7b812-9dad-11d1-80b4-00c04fd430c8'

NAMESPACE_URL

The predefined namespace UUID for URLs.

public mixed NAMESPACE_URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'

NAMESPACE_X500

The predefined namespace UUID for X.500 Distinguishing Names.

public mixed NAMESPACE_X500 = '6ba7b814-9dad-11d1-80b4-00c04fd430c8'

NIL_UUID

The special nil UUID.

public mixed NIL_UUID = '00000000-0000-0000-0000-000000000000'

SUPPORTED_VERSIONS

UUID versions that this class can generate.

public mixed SUPPORTED_VERSIONS = [0, 1, 2, 3, 4, 5, 6, 7, 15]

Versions 0 and 15 refer to the special nil and max UUIDs.

Properties

$clock_seq

protected static array<string|int, mixed> $clock_seq = []

The "clock sequence" values used for UUIDv1 and UUIDv6.

$namespace

protected static string $namespace

Binary form of a namespace UUID used for UUIDv3 and UUIV5.

The default value is the UUIDv5 for the executing script's URL. See self::setNamespace() for more information.

$node

protected static string $node

The "node ID" value used in UUIDv1 and UUIDv6.

$prev_timestamps

protected static array<string|int, mixed> $prev_timestamps = [1 => [], 6 => []]

The previously used timestamps for UUIDv1 and UUIDv6.

$timestamp

protected float $timestamp = 0.0

The Unix timestamp of this UUID.

$utc

protected static object $utc

A \DateTimeZone object for UTC.

$uuid

protected string $uuid

The generated UUID.

$version

protected int $version

The version of this UUID.

Methods

__construct()

Constructor.

public __construct([int $version = null ][, mixed $input = null ]) : mixed

Handling of the $input parameter varies depending on the $version:

  • For v3 and v5, $input must be a string or \Stringable object to hash.
  • For v1, v6, and v7, $input can be a Unix timestamp, a parsable date string, a \DateTimeInterface object, or null to use current time.
  • For v2, $input must be an array containing a 'domain' element and optional 'id' and 'timestamp' elements. (See $this->getHexV2() for more info.)
  • Otherwise, $input is ignored.

In general, using an arbitrary timestamp to create a time-based UUID is discouraged, because the timestamp is normally intended to refer to the moment when the UUID was generated. However, there are some situations in which UUIDs may need to be created from arbitrary timestamps in order to preserve or enforce a particular position in a sorting sequence, so the ability to do so is available.

Parameters
$version : int = null

The UUID version to create.

$input : mixed = null

Input for the UUID generator, if applicable.

__toString()

Returns the string representation of the generated UUID.

public __toString() : string
Return values
string

The UUID.

compress()

Convenience method to get the binary or short form of a UUID string.

public static compress(Stringable|string $input[, int $form = self::COMPRESS_BINARY ]) : string
Parameters
$input : Stringable|string

A UUID string. May be compressed or uncompressed.

$form : int = self::COMPRESS_BINARY

One of this class's COMPRESS_* constants.

Return values
string

The short form of the UUID string.

create()

Creates a new instance of this class.

public static create([int $version = null ][, mixed $input = null ]) : Uuid

This is just syntactical sugar to simplify method chaining and procedural coding styles, much like date_create() does for new \DateTime().

Parameters
$version : int = null

The UUID version to create.

$input : mixed = null

Input for the UUID generator, if applicable.

Return values
Uuid

A new Uuid object.

createFromString()

Creates an instance of this class from an existing UUID string.

public static createFromString(Stringable|string $input[, bool $strict = false ]) : Uuid

If the input UUID string is invalid, behaviour depends on the $strict parameter:

  • If $strict is false, a warning error will be triggered and an instance of this class for the nil UUID will be created.
  • If $strict is true, a fatal error will be triggered.
Parameters
$input : Stringable|string

A UUID string. May be compressed or uncompressed.

$strict : bool = false

If set to true, invalid input causes a fatal error.

Return values
Uuid

A Uuid object.

expand()

Convenience method to get the full form of a UUID string.

public static expand(Stringable|string $input) : string
Parameters
$input : Stringable|string

A UUID string. May be compressed or uncompressed.

Return values
string

The full form of the input.

getBinary()

Returns a binary representation of the UUID.

public getBinary() : string
Return values
string

16-byte binary string.

getNamespace()

Returns the fully expanded value of self::$namespace.

public static getNamespace() : string
Return values
string

A UUID string.

getShortForm()

Compresses $this->uuid to a 22- or 26-character string.

public getShortForm([bool $lowercase_only = false ]) : string

These short forms are URL-safe and maintain the same ASCII sort order as the original UUID string.

Parameters
$lowercase_only : bool = false

If true, only use lowercase letters. This results in a 26-character string, but it is easier for humans to work with than the shorter 22-character string.

Return values
string

The short form of the UUID.

getVersion()

Returns the version of this UUID.

public getVersion() : int
Return values
int

The version of this UUID.

setNamespace()

Sets self::$namespace to the binary form of a UUID.

public static setNamespace([Stringable|string|bool $ns = false ]) : void

If $ns is false and self::$namespace has not yet been set, a default namespace UUID will be generated automatically.

If $ns is a valid UUID string, that string will be used as the namespace UUID. A fatal error will be triggered if the string isn't a valid UUID.

If $ns is true, any existing value of self::$namespace will be replaced with the default value. This is helpful if you need to reset the value of self::$namespace after temporarily using a custom namespace.

The default namespace UUID is the UUIDv5 for Config::$scripturl.

See RFC 9562, section 6.5.

Parameters
$ns : Stringable|string|bool = false

Either a valid UUID, true to forcibly reset to the automatically generated default value, or false to use the current value (which will be set to the default if undefined). Default: false.

adjustTimestamp()

Adjusts a Unix timestamp to meet the needs of the this UUID version.

protected adjustTimestamp() : int
Return values
int

A timestamp value appropriate for this UUID version.

decodeBase32Hex()

Converts a base32hex string to hexadecimal.

protected static decodeBase32Hex(string $b32) : string

Note: base32hex, specified in RFC 4648, section 7, is the form of base32 that PHP's base_convert() produces. This is different from basic base32, which is specified in RFC 4648, section 6.

Parameters
$b32 : string

A base32hex string.

Return values
string

A hexadecimal string.

encodeBase32Hex()

Converts a hexadecimal string to base32hex.

protected static encodeBase32Hex(string $hex) : string

Note: base32hex, specified in RFC 4648, section 7, is the form of base32 that PHP's base_convert() produces. This is different from basic base32, which is specified in RFC 4648, section 6.

Parameters
$hex : string

A hexadecimal string.

Return values
string

A base32hex string.

getGregTimeParts()

Helper method for getHexV1 and getHexV6.

protected getGregTimeParts() : array<string|int, mixed>
Return values
array<string|int, mixed>

Components for the UUID.

getHexV1()

UUIDv1: Time-based (but not time-sortable) UUID version.

protected getHexV1(Stringable|string|int|float|null $input) : string

The 60-bit timestamp counts 100-nanosecond intervals since Oct 15, 1582, at 0:00:00 UTC (the date when the Gregorian calendar went into effect). The maximum date is Jun 18, 5623, at 21:21:00.6846975 UTC.

Uniqueness is ensured by appending a "clock sequence" and a "node ID" to the timestamp. The clock sequence is a randomly initialized value that can be incremented or re-randomized whenever necessary. The node ID can either be a value that is already guaranteed to be unique (typically the network card's MAC address) or a random value. In this implementation, both values are initialized with random values each time the script runs.

Parameters
$input : Stringable|string|int|float|null

Timestamp or date string.

Return values
string

32 hexadecimal digits.

getHexV2()

UUIDv2: DCE security version. Suitable only for specific purposes and is rarely used.

protected getHexV2(array<string|int, mixed> $input) : string

RFC 9562 does not describe this version. It just reserves UUIDv2 for "DCE Security version." Instead the specification for UUIDv2 can be found in the DCE 1.1 Authentication and Security Services specification.

The purpose of UUIDv2 is to embed information not only about where and when the UUID was created (via the node ID and timestamp), but also by whom it was created. This is accomplished by including a user, group, or organization ID and a type indicator (via a local domain ID and a local domain type indicator). This ability to know who created a UUID was apparently helpful for situations where a system needed to perform security checks related to the UUID value. For general purposes, however, this ability is not useful, and the trade-offs required to enable it are highly problematic.

The most significant problem with UUIDv2 is its extremely high collision rate. For any given combination of node, local domain type, and local domain identifier, it can only produce 64 UUIDs every 7 minutes.

This implementation uses random node IDs rather than real MAC addresses. This reduces the risk of UUIDv2 collisions occurring at a single site. Nevertheless, the collision risk remains high in global space.

Another problem is that DEC 1.1's specifications only describe the case where a UUIDv2 is generated on a POSIX system, and do not give guidance about what to do on non-POSIX systems. In particular, UUIDv2 tries to encode the user ID and/or group ID of the user who created the UUID, but these concepts may not be defined or available on non-POSIX systems. Instead, the meaning of all local domain types and local domain IDs is left undefined by the specification for non-POSIX systems.

If $input['id'] is set, it will be used as the local domain ID. If it is not set, the local domain ID will be determined based on the value of $input['domain']:

  • If 'domain' is 0, the ID will be the current user's ID number.
  • If 'domain' is 1, the ID will be the current user's group ID number.
  • If 'domain' is 2, the ID will be an organization ID. In this implementation, the organization ID is derived from self::$namespace.

If cross-platform support is desirable, then scripts generating UUIDv2s should always provide a value in $input['id'] rather than relying on automatically determined values. ... Or better yet, don't use UUIDv2.

Parameters
$input : array<string|int, mixed>

array

Return values
string

32 hexadecimal digits.

getHexV3()

UUIDv3: Creates a UUID for a name within a namespace using an MD5 hash.

protected getHexV3(string $input) : string
Parameters
$input : string

The input string.

Return values
string

32 hexadecimal digits.

getHexV4()

UUIDv4: Creates a UUID from random data.

protected getHexV4() : string
Return values
string

32 hexadecimal digits.

getHexV5()

UUIDv5: Creates a UUID for a name within a namespace using an SHA-1 hash.

protected getHexV5(string $input) : string
Parameters
$input : string

The input string.

Return values
string

32 hexadecimal digits.

getHexV6()

UUIDv6: Time-sortable UUID version.

protected getHexV6(Stringable|string|int|float|null $input) : string

The timestamp component is monotonic and puts the most significant bit first, so sorting these UUIDs lexically also sorts them chronologically.

The 60-bit timestamp counts 100-nanosecond intervals since Oct 15, 1582, at 0:00:00 UTC (the date when the Gregorian calendar went into effect). The maximum date is Jun 18, 5623, at 21:21:00.6846975 UTC.

Uniqueness is ensured by appending a "clock sequence" and a "node ID" to the timestamp. The clock sequence is a randomly initialized value that can be incremented or re-randomized whenever necessary. The node ID can either be a value that is already guaranteed to be unique (typically the network card's MAC address) or a random value. In this implementation, both values are initialized with random values each time the script runs.

Parameters
$input : Stringable|string|int|float|null

Timestamp or date string.

Return values
string

32 hexadecimal digits.

getHexV7()

UUIDv7: Improved time-sortable UUID version.

protected getHexV7(Stringable|string|int|float|null $input) : string

The timestamp component is monotonic and puts the most significant bit first, so sorting these UUIDs lexically also sorts them chronologically.

The 48-bit timestamp measures milliseconds since the Unix epoch. The maximum date is Aug 01, 10889, at 05:31:50.655 UTC.

Uniqueness is ensured by appending 74 random bits to the timestamp.

Parameters
$input : Stringable|string|int|float|null

Timestamp or date string.

Return values
string

32 hexadecimal digits.

setTimestamp()

Sets $this->timestamp to a microsecond-precision Unix timestamp.

protected setTimestamp([Stringable|string|int|float $input = 'now' ]) : void
Parameters
$input : Stringable|string|int|float = 'now'

A timestamp or date string. Default: 'now'.


        
On this page

Search results