Developer Documentation
PHP
Updated September 19, 2026

Generate and Work with UUIDs in PHP

Generate, parse, format, and validate UUIDs safely in PHP.

UUIDs are 128-bit identifiers standardized by RFC 9562. UUIDv4 is random and broadly supported; newer UUID versions add other generation properties while keeping the same canonical textual shape.

Quick Start#

The following example uses the standard PHP API or a widely used package for this task.

Using ramsey/uuid#

PHP
1<?php2// Install first: composer require ramsey/uuid3use Ramsey\Uuid\Uuid;45$id = Uuid::uuid4();6echo $id->toString() . PHP_EOL;

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Validate and parse#

PHP
1<?php2use Ramsey\Uuid\Uuid;34if (Uuid::isValid($input)) {5    $uuid = Uuid::fromString($input);6    echo $uuid->toString();7}

Important Notes#

Use a maintained UUID library instead of implementing random bit layout yourself. Store native UUID types in databases when your driver/database supports them.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#