Skip to content

Instantly share code, notes, and snippets.

@dpk
Created November 21, 2010 11:18
Show Gist options
  • Save dpk/708653 to your computer and use it in GitHub Desktop.
Save dpk/708653 to your computer and use it in GitHub Desktop.
Generate v4 UUID
<?php
function uuidgen() { // generate a version 4 UUID
// clarification: a v4 UUID is in the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx
// where any x is a random alphanumeric character
// 4 is the numeral 4
// and y may only by one of 8, 9, A or B
$format = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx';
$x = '1234567890ABCDEF';
$y = '89AB';
$uuid = '';
$format = str_split($format);
foreach ($format as $char) {
if ($char == 'x' || $char == 'y') {
mt_srand(make_seed()); // seed the random generator
$uuid .= ${$char}[mt_rand(0, strlen(${$char})-1)];
} else {
$uuid .= $char;
}
}
return $uuid;
}
function make_seed() { // http://cl.ly/3L23
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment