Skip to content

Instantly share code, notes, and snippets.

@JanTvrdik
Last active Feb 14, 2018
Embed
What would you like to do?
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