Generate UUIDs in PHP
Complete code tutorial with examples and best practices
[ Code Example - Quick Summary ]
Language: PHP
What: Generate UUIDs in PHP using the popular <code>ramsey/uuid</code> library. Supports UUID v1, v4, v5, and v7 with excellent performance and RFC 4122 compliance.
Try it: Use our interactive Uuids generator or integrate this code into your PHP application.
Generate UUIDs in PHP using the popular ramsey/uuid library. Supports UUID v1, v4, v5, and v7 with excellent performance and RFC 4122 compliance.
Looking for other languages? Check our code examples in
JavaScript
,
Python
,
Java
,
C#
,
C++
,
Ruby
and
Go
or use our interactive web generator.
PHP Code Example
<?php
require 'vendor/autoload.php';
use Ramsey\Uuid\Uuid;
// Generate UUID v4 (random)
$uuid4 = Uuid::uuid4();
echo $uuid4->toString(); // Example: 3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f
// Generate UUID v7 (timestamp-ordered, recommended for databases)
$uuid7 = Uuid::uuid7();
echo $uuid7->toString(); // Example: 018e5e1a-7b2c-7d4f-9a3e-8c7f6e5d4c3b
// Generate UUID v5 (namespaced)
$namespace = Uuid::NAMESPACE_DNS;
$name = 'example.com';
$uuid5 = Uuid::uuid5($namespace, $name);
echo $uuid5->toString(); // Always same: cfbff0d1-9375-5685-968c-48ce8b15ae17
// Parse and validate UUID
$uuidString = '3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f';
if (Uuid::isValid($uuidString)) {
$uuid = Uuid::fromString($uuidString);
echo $uuid->getVersion(); // Outputs: 4
}
[EXPLANATION]
Install via Composer: composer require ramsey/uuid. UUID v4 uses random bytes for maximum uniqueness. UUID v7 is timestamp-ordered, ideal for database primary keys (better indexing than v4). UUID v5 is deterministic based on namespace + name.
Expected Output
3d6f9e64-7d8a-4c3e-8f2b-1a4e5c6d7e8f 018e5e1a-7b2c-7d4f-9a3e-8c7f6e5d4c3b cfbff0d1-9375-5685-968c-48ce8b15ae17 4
Common Use Cases
- Database primary keys (use UUID v7 for better indexing)
- Distributed systems unique identifiers
- API request/response tracking IDs
- File upload unique names
- Session identifiers
- Event sourcing event IDs
Important Notes
- UUID v7 is recommended for new projects (timestamp-ordered)
- UUID v4 is widely used but less database-friendly than v7
- Ramsey UUID is the standard PHP library (10M+ downloads/month)
- Store UUIDs as BINARY(16) in MySQL for optimal performance
Try Our Interactive Generator
Don't want to write code? Use our free web-based Uuids generator with instant results.
TRY UUIDS GENERATOR →Other Programming Languages
View Uuids generation code examples in JavaScript
View Uuids generation code examples in Python
View Uuids generation code examples in Java
View Uuids generation code examples in C#
View Uuids generation code examples in C++
View Uuids generation code examples in Ruby
View Uuids generation code examples in Go