DrUUID RFC 9562 library manual

Preface

"DrUUID" is an implementation for PHP of---and associated API for---the data format described in RFC 9562, Universally Unique IDentifiers (UUIDs). It is able to mint new UUIDs, import existing UUIDs, extract information from UUIDs, and compare two UUIDs for bit-exact equality.

The API is designed to be as simple as possible, with an implementation as accurate as practical given the limits of PHP. All other concerns, including PHP compatibility, efficiency and extensibility are secondary.

Questions and comments are very welcome, and should be directed to the author via his Web site.

Download current version (archives)

Table of contents

Prefaces

  1. Preface
  2. Table of contents
  3. Features
  4. Requirements
  5. Conformance exceptions

Body

  1. Documentation note
  2. The API
    1. UUID::mint()
      1. Version 1
      2. Version 3
      3. Version 4
      4. Version 5
      5. Version 6
      6. Version 7
      7. Version 8
    2. UUID::import()
    3. UUID::compare()
    4. UUID::mintStr()
  3. The UUID object
    1. Public properties
  4. Using custom stable storage implementations
    1. UUID::registerStorage()
    2. The UUIDStorage interface

Appendices

  1. Defined constants
  2. Credits and licensing
  3. Revision history

Features

Requirements

Conformance exceptions

Documentation note

This manual often makes references to binary and hexdecimal strings for input and output. For the sake of simplicity please assume that such strings are always in network order (big-endian).

For methods accepting a UUID as an argument, the UUID may be:

This manual often makes reference to invalid UUIDs. For simplicity this is merely any string more or less than 16 bytes long. DrUUID performs no other validation on UUIDs.

The API

The core DrUUID API consists of four static methods: UUID::mint(), UUID::import(), UUID::compare() as well as UUID::mintStr(). Of these UUID::mint() and UUID::import() return an instance of the UUID class.

UUID::mint()

UUID UUID::mint( [int version [, ... ]] )

The UUID::mint() method generates ("mints", like coinage) a new UUID. It is capable of producing Version 1 (time-based), Version 3 (MD5 hash-based), Version 4 (random), Version 5 (SHA-1 hash-based), Version 6 (ordered time-based), and Version 7 (Unix time-based) UUIDs. Its argument list is generic: required and optional argument depend upon the specified version to produce. For backwards-compatibility reasons Version 1 UUIDs are produced unless otherwise specified, but using Version 7 is recommended.

Version 1

UUID UUID::mint( 1 )

Version 1 UUIDs are generated based on the current time and a MAC address (called a node).

If specified, node should be either a 6-byte binary string or a 12-character hexadecimal string (with or without separators) representing a MAC address. DrUUID does not attempt to detect the host's MAC address. Invalid nodes will throw an exception.

The sequence argument specifies a clock sequence and should be a two-byte binary string. This should only be used for debugging. Invalid sequences will throw an exception.

Finally, the time argument may be specified to employ a past or future time (as a Unix timestamp with microseconds like that returned by microtime() for example) instead of the curent time. This should only be used for debugging and never used to generate UUIDs for any purpose but testing. Input which cannot be parsed as a timestamp will throw an exception.

Version 3

UUID UUID::mint( 3, string name, UUID|string namespace )

Version 3 UUIDs are generated based upon a an MD5 hash of an arbitrary name and its associated name-space. For example the name "www.example.com" is within the DNS namespace, much as "Canada" is within a name-space of the world's countries. A name/namespace pair will predictably generate the same UUID.

The name argument is an arbitrary name and should be in a binary form appropriate for namespace. It is the responsibility of the user to assure the proper conversion to binary form. For many namespaces (like the DNS) the appropriate representation is plain text and therefore no conversion is required.

The namespace argument is itself a UUID; invalid UUIDs will throw an exception.

Note that the continued use of Version 3 UUIDs is discouraged: Version 5 UUIDs should be used instead whenever possible.

Version 4

UUID UUID::mint( 4 )

Version 4 UUIDs are generated from random numbers. Save for embedded version information they are completely random.

Version 5

UUID UUID::mint( 5, string name, UUID|string namespace )

Version 5 UUIDs are generated based upon a an SHA-1 hash of an arbitrary name and its associated name-space. For example the name "www.example.com" is within the DNS namespace, much as "Canada" is within a name-space of the world's countries. A name/namespace pair will predictably generate the same UUID.

The name argument is an arbitrary name and should be in a binary form appropriate for namespace. It is the responsibility of the user to assure the proper conversion to binary form. For many namespaces (like the DNS) the appropriate representation is plain text and therefore no conversion is required.

The namespace argument is itself a UUID; invalid UUIDs will throw an exception.

Version 5 UUIDs are preferred over Version 3 UUIDs.

Version 6

UUID UUID::mint( 6 )

Version 6 UUIDs are generated based on the current time and a MAC address (called a node), the same as Version 1 UUIDs. Version 6 UUIDs differ only in that they will sort chronologically.

See the description of Version 1 UUIDs above for usage details.

Version 7

UUID UUID::mint( void )
UUID UUID::mint( 7 )

Version 7 UUIDs (the default type) are generated based on the current time using a simpler algorithm than Version 1 or Version 6 UUIDs. Version 7 is the recommended form to use for new software.

The time argument may be specified to employ a past or future time (as a Unix timestamp with microseconds like that returned by microtime() for example) instead of the curent time. This should only be used for debugging and never used to generate UUIDs for any purpose but testing. Input which cannot be parsed as a timestamp will throw an exception.

Version 8

Support for Version 8 UUIDs has been stubbed in, but as their contents have no agreed-upon interpretation attempting to create one will throw an exception.

A subclass may implement Version 8 UUIDs by overriding the mintCustom() and __get() methods to implement necessary logic.

UUID::import()

UUID UUID::import( string uuid )

The UUID::import() method imports a UUID string as a UUID object. Invalid UUIDs will throw an exception.

UUID::compare()

bool|null UUID::compare( UUID|string uuid1, UUID|string uuid2 )

The UUID::compare() method compares two UUIDs for equivalency. If both UUIDs, as binary numbers, are equal, the method returns true. The method will return null if either arguments is not a valid UUID.

This method is useful for determining if two different UUID representations (eg. canonical string, lowercase hex string, uppercase hex string, binary, URN) are in fact the same UUID.

UUID::mintStr()

string UUID::mintStr( [int version [, ... ] )

The UUID::mintStr() method performs the same functions as the UUID::mint() method, but returns the UUID directly as a string in canonical form.

The UUID object

UUID objects cannot be instantiated manually; they must be created via UUID::mint() or UUID::import(). When cast to a string a UUID object will be rendered in the canonical string form (eg. 550e8400-e29b-41d4-a716-446655440000). They have no public methods, but do have a number of public properties:

Public properties

bytes
A 16-byte binary string representation of the UUID.
hex
A 32-character hexadecimal representation of the UUID. Neither octets nor fields are ever padded and high digits are always lowercased.
string
The canonical string representation of the UUID, with high hexadecimal digits always lowercased.
urn
The UUID formatted as an URN.
version
The UUID's version (eg. 1, 3, 4, 5, 6, 7).
variant
The UUID's variant. For RFC 9562 UUIDs this is always 1.
node
The MAC address associated with the UUID. Only applicable to Version 1 and Version 6 identifiers.
time
The time at which the UUID was generated, as a fixed-point Unix timestamp string with seven- (Version 1 and Version 6) or three-digit (Version 7) sub-second precision. Only applicable to Version 1, Version 6, and Version 7 identifiers.

Using custom stable storage implementations

DrUUID only includes a basic implementation of in-memory storage for Version 1 and Version 6 UUIDs which is consistent with Section 6.3 of RFC 9562. This implementation, however, is not sufficient for optimal uniqueness for Version 1 or Version 6 UUIDs. If using these types (Version 7 or Version 4 are preferred for new applications), a custom storage implementation can be provided to DrUUID for holding state.

UUID::registerStorage()

void UUID::registerStorage( UUIDStorage store )

The class_name argument must be the name of a defined class which imprements the UUIDStorage interface, described below. Any further arguments will be passed to UUID::initStorage().

If no supplementary arguments are passed, UUID::initStorage() must be called before the custom storage may be used.

The UUIDStorage interface

interface UUIDStorage {
 public function getNode(): ?string;
 public function getSequence(string $timestamp, string $node): ?string;
 public function setSequence(string $sequence): void;
 public function setTimestamp(string $timestamp): void;
 const maxSequence = 16383; // 00111111 11111111
}

The UUIDStorage interface defines a set of methods which DrUUID ill call during the generation of Version 1 and Version 6 UUIDs in a predictable order to query storage and write data. The order of the method calls is as follows:

  1. Retrieve the last known node ID (MAC address) by calling getNode()
    • The storage may attempt to retrieve the actual MAC address; otherwise it returns the stored one, or null
  2. If the node ID is null because an existing value is not available, generate a new random node ID
  3. Retrieve the clock sequence by calling getSequence(), passing the timestamp and node ID
    • The storage invalidates any stored clock sequence if the current node ID does not match that stored
    • The storage increments the stored clock sequence before returning it if the timestamp provided is not newer than that stored
  4. If the clock sequence is null because an existing value was not available or was invalidated, generate a new random clock sequence and call setSequence()
  5. Call setTimestamp() to update the stored timestamp, signalling the end of communication

The following subsections serve as implementation notes for the interface's methods.

getNode()

As DrUUID is unable to retrieve the system's MAC address, it calls the getNode() method, which might implement a means of doing so or retrieve one from storage. If it does return a value, it should be formatted as six bytes, in big-endian order (the reverse of conventional hexdecimal pair representation).

getSequence()

The getSequence() method is the heart of the interface, taking as input the target timestamp (as a number of 100ns ticks since the Unix epoch) and the node ID (as a six-byte string). Output should be a two-byte string, with the two most significant bits set to zero.

Per Section 5.1 of RFC 9562, the clock sequence should be randomized if the node ID changes, and should be incremented if the target timestamp is lower than that in storage. Due to the limits of 32-bit systems and the difficulties inherent in comparing floating-point numbers, the input timestamp is always a string with integer precision.

setSequence()

This method simply alerts the storage of a new clock sequence, if either the user has supplied a sequence or the storage failed to return a result. Input is a two-byte string; no return value is required.

setTimestamp()

The method serves as a marker that communication with the storage is complete and any buffered data may be written to stable storage if appropriate. Input is a string representation of the number of 100ns ticks since the Unix epoch.

Predefined constants

For convenience DrUUID includes a few class constants representing the registry of UUID namespaces defined in Section 6.6 of RFC 9562 for use in Version 3 or 5 UUIDs.

These constants are briefly documented in this appendix.

Namespace constants
Constant Namespace description UUID
UUID::nsDNS DNS hostnames (e.g. "www.example.com") 6ba7b810-9dad-11d1-80b4-00c04fd430c8
UUID::nsURL Any valid URL (e.g. "http://www.example.com/example.html") 6ba7b811-9dad-11d1-80b4-00c04fd430c8
UUID::nsOID An ISO Object Identifier 6ba7b812-9dad-11d1-80b4-00c04fd430c8
UUID::nsX500 An X.500 Distinguished Name 6ba7b814-9dad-11d1-80b4-00c04fd430c8

Credits and licensing

DrUUID and its manual (i.e. this document) were written by J. King. They are both governed by the following license:

Copyright (c) 2009, 2025 J. King

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

This manual's stylesheet was written by Dustin Wilson. It is licensed under the Creative Commons Attribution license (v2.5).

This software is dedicated to Seung Park. HLN forever!

Revision history

2025-12-11 (4.0.0)
This release constitutes code clean-up and includes many backwards-incompatible changes. The basic API remains largely unchanged, but there are many differences around the edges: Note that in the above all references to the UUID::mint() method should be understood to include the UUID::mintStr() method as well.
2025-12-10 (3.1.0)
2017-02-09 (3.0.0)
2014-09-06
Major enhancements:
2011-03-20
Refined the generation of Version 1 UUIDs. This sees the addition of the sequence and time parameters to UUID::mint(1), as well as the addition of UUID::seq().
2010-02-15
Fixed bug in UUID::import as reported by Sander van Lambalgen.
2009-11-26
Fixed previously non-functional UUID::compare() method. Also allowed input UUIDs to be RFC 4122 URNs.
2009-11-11
Various changes:
2009-09-28
Fixed a minor bug preventing /dev/urandom from being used. Reported by Rubén Marrero.
2009-04-13
Fixed two serious bugs in Version 5 generation and string casting.
2009-04-11
First release.