
Voilà une manière simple de générer un UUID en PHP… ça peut toujours servir 🙂
function gen_uuid () {
if (function_exists('random_bytes')) {
// code PHP 7
$data = random_bytes(16);
} elseif (function_exists('openssl_random_pseudo_bytes')) {
// code PHP 5.3 et nécessite la librairie Open SSL
$data = openssl_random_pseudo_bytes(16);
} else {
// au pire, on va se rabattre sur la solution actuelle
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)
);
}
$data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 100
$data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6 & 7 to 10
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}