Skip to content

Instantly share code, notes, and snippets.

@lcherone
Last active December 7, 2017 19:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lcherone/a4be0c47004d22ce3716f465a186976a to your computer and use it in GitHub Desktop.
Save lcherone/a4be0c47004d22ce3716f465a186976a to your computer and use it in GitHub Desktop.
guidv4 with random_bytes()
<?php
function guidv4()
{
if (function_exists('random_bytes') === true) {
$bytes = random_bytes(16);
} elseif (function_exists('openssl_random_pseudo_bytes') === true) {
$bytes = openssl_random_pseudo_bytes(16);
} elseif (function_exists('mcrypt_create_iv') === true) {
$bytes = mcrypt_create_iv(16, MCRYPT_DEV_URANDOM);
} elseif (function_exists('com_create_guid') === true) {
return trim(com_create_guid(), '{}');
} else {
return sprintf(
'%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(16384, 20479),
mt_rand(32768, 49151),
mt_rand(0, 65535),
mt_rand(0, 65535),
mt_rand(0, 65535)
);
}
$bytes[6] = chr(ord($bytes[6]) & 0x0f | 0x40); // set version to 0100
$bytes[8] = chr(ord($bytes[8]) & 0x3f | 0x80); // set bits 6-7 to 10
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment