Skip to content

Instantly share code, notes, and snippets.

@JanTvrdik
Last active February 14, 2018 14:11
Show Gist options
  • Save JanTvrdik/655b31e78e998bb468c7f8f8cfe4b3b6 to your computer and use it in GitHub Desktop.
Save JanTvrdik/655b31e78e998bb468c7f8f8cfe4b3b6 to your computer and use it in GitHub Desktop.
PHP Fast and simple UUID v4 generator
<?php
function generateUuidWithoutDashes(): string
{
$uuidBin = random_bytes(16);
$uuidBin &= "\xFF\xFF\xFF\xFF\xFF\xFF\x0F\xFF\x3F\xFF\xFF\xFF\xFF\xFF\xFF\xFF";
$uuidBin |= "\x00\x00\x00\x00\x00\x00\x40\x00\x80\x00\x00\x00\x00\x00\x00\x00";
$uuidHex = bin2hex($uuidBin);
return $uuidHex;
}
function generateUuidWithDashes(): string
{
$uuidBin = random_bytes(18);
$uuidBin &= "\xFF\xFF\xFF\xFF\x0F\xFF\xF0\x0F\xFF\x03\xFF\xF0\xFF\xFF\xFF\xFF\xFF\xFF";
$uuidBin |= "\x00\x00\x00\x00\x00\x00\x00\x40\x00\x08\x00\x00\x00\x00\x00\x00\x00\x00";
$uuidHex = bin2hex($uuidBin);
$uuidHex[8] = $uuidHex[13] = $uuidHex[18] = $uuidHex[23] = '-';
return $uuidHex;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment