wp_generate_uuid4(): string

Generates a random UUID (version 4).


string UUID.

Top ↑


File: wp-includes/functions.php. View all references

function wp_generate_uuid4() {
	return sprintf(
		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 )

Top ↑


Version Description
4.7.0 Introduced.

Top ↑

User Contributed Notes

  1. Skip to note 1 content
    Contributed by Philipp Stracker

    Sample result: 11223344-5566-7788-99AA-BBCCDDEEFF00

    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
  2. Skip to note 2 content
    Contributed by thanasisxan

    It should be noted that using this function to generate uuid’s WILL lead to collisions by creating duplicates, I found out not the fun way.

    The function mt_rand() used will always produce the same sequence of random numbers given the same seed. So every time a seed is repeated, the same exact UUID is generated.

    To get around this, you would need to seed it using something else for example:

    mt_srand( crc32( serialize( array( microtime( true ), 'USER_IP', 'ETC' ) ) ) );

You must log in before being able to contribute a note or feedback.