Skip to content

How to generate a UUID in PHP

PHP is a server-side programming language used by a wide variety of industries to create full-stack web applications. It is used to manage dynamic content, databases, session tracking, and even build entire e-commerce sites.

Generating a UUID in PHP

Here is a function to generate a UUID in PHP:

php
function generate_uuid() {
    return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
        random_int(0, 0xffff), random_int(0, 0xffff),
        random_int(0, 0xffff),
        random_int(0, 0x0fff) | 0x4000,
        random_int(0, 0x3fff) | 0x8000,
        random_int(0, 0xffff), random_int(0, 0xffff), random_int(0, 0xffff)
    );
}

$uuid = generate_uuid();

This function uses the random_int() function to generate cryptographically secure random integers and the sprintf() function to format the UUID string. You can call this function to generate a UUID like this:

$uuid = generate_uuid();

Explanation

  • The generate_uuid() function defines a new function that generates a UUID.
  • The return statement returns the value of the expression that follows it.
  • The sprintf() function formats a string with the given arguments. In this case, it formats the UUID string with the given hexadecimal values.
  • The random_int() function generates cryptographically secure random integers. In this case, it generates random integers between 0 and 0xffff.
  • The | operator performs a bitwise OR operation on the generated integers to set specific bits in the UUID string.