Generate a GUID / UUID

A GUID is a 16-byte a calculated pseudo-unique identifier. It is usually formatted as a hexadecimal string with curly braces and dashes:

{3F2504E0-4F89-11D3-9A0C-0305E82C3301}

A very simple implementation for PHP is this:

generateguid.inc.php
function generateGUID($braces=false) {
    $charset = '0123456789ABCDEF';   // default way - only hex digits
    //$charset = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';  // strong GUID(wtf??)
    $length = 16 * 2;  // 16 Bytes x 2 Hex-Digits per Byte
    $type = strtoupper(dechex(bindec('1000')));  // (0xxx = NCS backward compat., 10xx = Standard, 110x = M$ backward compat., 111x = future use)
    $version = '4';  // algorithm: random number
 
    // XXX: $type setting should ignore the remaining bit/bits (marked 'x' in comment above)
    //      see http://en.wikipedia.org/wiki/Globally_Unique_Identifier for details (esp.: Data3, Data4 versioning bits)
 
    $result = '';
    for ($i=0;$i<$length;$i++) {
        $result .= $charset{mt_rand(0, strlen($charset)-1)};
    }
 
    $result{18} = $type;
    $result{12} = $version;
 
    $result = substr($result, 0, 8) . '-' . substr($result, 8, 4) . '-' . substr($result, 12, 4) . '-' . substr($result, 16, 4) . '-' . substr($result, 20);
    if ($braces) $result = '{' . $result . '}';
    return $result;
}

But since PHP 5 you can use the com_create_guid function or the uuid PECL package.


 
snippets/php/generate-guid.txt · Last modified: 2010-01-15 14:42.36 by mbirth
 
Except where otherwise noted, content on this wiki is licensed under the following license:CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki Contents powered by Club-Mate Contents powered by BassDrive.com Labelled with ICRA