wp_generate_uuid4(): string

Generates a random UUID (version 4).

Return

string UUID.

Source

function wp_generate_uuid4() {
	static $backup_randomizer = false;
	$randomizer               = function_exists( 'wp_rand' ) ? 'wp_rand' : $backup_randomizer;

	if ( false === $randomizer ) {
		try {
			random_int( 0, 15705 );
			$backup_randomizer = 'random_int';
		} catch ( Exception $e ) {
			$backup_randomizer = 'mt_rand';
		}
		$randomizer = $backup_randomizer;
	}

	return sprintf(
		'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
		$randomizer( 0, 0xffff ),
		$randomizer( 0, 0xffff ),
		$randomizer( 0, 0xffff ),
		$randomizer( 0, 0x0fff ) | 0x4000,
		$randomizer( 0, 0x3fff ) | 0x8000,
		$randomizer( 0, 0xffff ),
		$randomizer( 0, 0xffff ),
		$randomizer( 0, 0xffff )
	);
}

Changelog

VersionDescription
7.0.0Uses wp_rand if available.
4.7.0Introduced.

User Contributed Notes

  1. Skip to note 5 content

    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' ) ) ) );
  2. Skip to note 6 content

    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:

    <?php
    $uuid36 = wp_generate_uuid4();             // a938e855-483e-48c7-9b98-f41e90511f77
    $uuid32 = str_replace( '-', '', $uuid36 ); // a938e855483e48c79b98f41e90511f77
  3. Skip to note 7 content

    The probability of this function providing same result is high and the use of mt_rand() does not ensure true uniqueness.
    You can use this function as a work-around.

        function wpdocs_secure_uuid4() {
            // Generate 16 bytes (128 bits) of random data.
            $data = random_bytes( 16 );
        
            // Set the version and variant bits.
            $data[6] = chr( ( ord($data[6] ) & 0x0f ) | 0x40 ); // Set version to 4 (0100).
            $data[8] = chr(( ord( $data[8] ) & 0x3f ) | 0x80 ); // Set variant to 10xx.
        
            // Split the binary data into segments for UUID formatting.
            $parts = unpack( 'N1a/n1b/n1c/n1d/N1e', $data );
        
            // Format the UUID using the unpacked values.
            return sprintf(
                '%08x-%04x-%04x-%04x-%012x',
                $parts['a'], $parts['b'], $parts['c'], $parts['d'], $parts['e']
            );
        }
  4. Skip to note 8 content

    This should not be used. It’s worse only bad.

    There is a limit of seeds to 32 bit numbers and so with mt_seed() called in the same way on each load of a script, there are only 2^32 different uuids. So the a collision can occur in around 80,000 calls.

    Its worse than that, though, as running in a container environment might mean lots of seed reusage, so collisions will occur all the time! (see the PHP dot net docs for mt_srand()).

    Caution
    Because the Mt19937 (“Mersenne Twister”) engine accepts only a single 32 bit integer as the seed, the number of possible random sequences is limited to just 232 (i.e. 4,294,967,296), despite Mt19937’s huge period of 219937-1.

    When relying on either implicit or explicit random seeding, duplications will appear much earlier. Duplicated seeds are expected with 50% probability after less than 80,000 randomly generated seeds according to the birthday problem. A 10% probability of a duplicated seed happens after randomly generating roughly 30,000 seeds.

    This makes Mt19937 unsuitable for applications where duplicated sequences must not happen with more than a negligible probability. If reproducible seeding is required, both the Random\Engine\Xoshiro256StarStar and Random\Engine\PcgOneseq128XslRr64 engines support much larger seeds that are unlikely to collide randomly. If reproducibility is not required, the Random\Engine\Secure engine provides cryptographically secure randomness.

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