Generate a UUID in PHP

PHP is one of the more popular programming languages in the world.

First released in 1995 as a way to build dynamic web applications, PHP is a dynamically typed scripting language with similarities to Perl and C. Although considered a general purpose programming language, PHP is primarily used for building websites.

How to Generate a UUID in PHP

PHP does not have built-in support for generating RFC 4122 compliant UUIDs. The function, uniqid(), is not a sufficient replacement for generating RFC 4122 compliant UUIDs as it may not always generate a unique value (especially if your computer is fast) and it can only generate a maximum of 23 characters.

However, below you'll find two, viable 3rd-party solutions for generating RFC 4122 compliant UUIDs in PHP.

1. Roll-Your-Own UUID Generation Function in PHP

This small helper function generates RFC 4122 compliant Version 4 UUIDs.

function guidv4($data = null) {
// Generate 16 bytes (128 bits) of random data or use the data passed into the function.
$data = $data ?? random_bytes(16);
assert(strlen($data) == 16);
// Set version to 0100
$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
// Set bits 6-7 to 10
$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
// Output the 36 character UUID.
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}

Notes

  • This function requires PHP 7 or later because of the use of the function random_bytes on line #3.
  • If you're using PHP 5 or earlier and have the openssl extension installed, you could use openssl_random_pseudo_bytes(16), instead of random_bytes(16) on line #3.
  • Credits go to this answer on Stackoverflow for this solution.
  • An example usage of this function would look like this:
    $myuuid = guidv4();
    echo $myuuid;

2. Use the ramsey/uuid PHP Library

If you're using Composer for managing dependencies in your PHP project, you can use the ramsey/uuid PHP library for generating UUIDs.

To get started with the library, you can install and add it to your project like this:

% composer require ramsey/uuid

Now you can use it in your PHP project. Here is a small example of generating a UUID with this library:

use Ramsey/Uuid/Uuid;
$myuuid = Uuid::uuid4();
printf("Your UUID is: %s", $myuuid->toString());

How can we improve this page? Let us know!




The UUIDs generated by this site are provided AS IS without warranty of any kind, not even the warranty that the generated UUIDs are actually unique. You are responsible for using the UUIDs and assume any risk inherent to using them. You are not permitted to use the UUIDs generated by this site if you do not agree to these terms. Do not use any UUIDs found on cached versions of this page.

The UUIDs generated by this site conform to RFC 4122 whenever possible.
Read more about UUIDs at Wikipedia.
Check out our developer API.

Copyright © 2021 TransparenTech LLC. All Rights Reserved. Contact Us.