wp_generate_uuid4()WP 4.7.0

Generates an identifier - a random unique string consisting of letters and numbers. Creates UUID (Universally unique identifier) version 4.

It works based on 8 functions mt_rand() and has the format %04x%04x-%04x-%04x-%04x-%04x%04x%04x%04x - consists of 5 parts:

  • Part 1 consists of 8 characters.
  • 2,3,4 parts consist of 4 characters each, all different.
  • Part 5 consists of 12 characters.

For example:

4c585b5e-5220-4b1d-92e2-316f88210482
UUID explanation

A UUID represents a 128-bit value (16 bytes): It contains four 4-byte digits that are represented in hex notation, and are segmented by 4 - symbols. The total length is 36 characters.

The - symbols appear after byte 4, byte 6, byte 8 and after byte 10.

Because it’s a hex-value, a UUID should be treated in a case-insensitive manner:
11223344-5566-7788-99AA-BBCCDDEEFF00 is identical to 11223344-5566-7788-99aa-bbccddeeff00.

This function always returns a lower-case string.

To get a 32-character string (same as MD5) you could use:

$uuid36 = wp_generate_uuid4();             // a938e855-483e-48c7-9b98-f41e90511f77
$uuid32 = str_replace( '-', '', $uuid36 ); // a938e855483e48c79b98f41e90511f77

Use wp_is_uuid(), to check if a string is a UUID code.

Use the standard PHP function uniqid() if you want a simplified version of the UUID.

1 time — 0. sec (speed of light) | 50000 times — 0.07 sec (speed of light) | PHP 7.1.5, WP 4.9.4

No Hooks.

Return

String. UUID.

Usage

wp_generate_uuid4();

Examples

0

#1 Create and display the UUID [auto-translate]

echo wp_generate_uuid4();
//> 9d9c81fc-4233-4b6e-98aa-b553d7d200ab

Changelog

Since 4.7.0 Introduced.

wp_generate_uuid4() code WP 6.4.3

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