Universally Unique Identifier is an identifier standard which is used in a varieties of software construction. When I was writing the RSS Writer class for Orchid, I needed to generate UUID to implement with ATOM id. I searched the web for a simple solution, but didn’t find any that suffices my need. Then I wrote the following function to generate it. I’ve use the standard of canonical format here.

Let’s take a look what Wikipedia has to say about the format of UUID :

A UUID is a 16-byte (128-bit) number. The number of theoretically possible UUIDs is therefore 216*8 = 2128 = 25616 or about 3.4 × 1038. This means that 1 trillion UUIDs would have to be created every nanosecond for 10 billion years to exhaust the number of UUIDs.

In its canonical form, a UUID consists of 32 hexadecimal digits, displayed in 5 groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters.

Enough said. Here is the function.

/**
  * Generates an UUID
  * 
  * @author     Anis uddin Ahmad <admin@ajaxray.com>
  * @param      string  an optional prefix
  * @return     string  the formatted uuid
  */
  function uuid($prefix = ) 
  {
    $chars = md5(uniqid(rand()));
    $uuid  = substr($chars,0,8) . ‘-’;
    $uuid .= substr($chars,8,4) . ‘-’;
    $uuid .= substr($chars,12,4) . ‘-’;
    $uuid .= substr($chars,16,4) . ‘-’;
    $uuid .= substr($chars,20,12);
    
    return $prefix . $uuid;
  }

Example of using the function -

//Using without prefix.
echo uuid(); //Returns like ‘1225c695-cfb8-4ebb-aaaa-80da344e8352′ 
 
//Using with prefix
echo uuid(‘urn:uuid:’);//Returns like ‘urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344e8352′
 

See you.

UPDATE : The PHP Universal Feed Generator class, for which I wrote this function is released.