Search the blog

A GUID is a globally unique identifier; it’s a 128-bit hexadecimal string. There are so many possible GUIDs that you can assign them to any data record and be fairly confident that no one else on the planet (hence the word “global”) will be using the same GUID. (Contrast this with an auto-increment int primary key in a database)

To create a GUID we need a 128-bit hashing function (MD5 or RIPEMD-128 would do) and something random and unique to hash. I’m combining the URL and a unique ID based on the current time. uniqid on its own only creates 52 bits so we prefix a random number, increase the entropy and prefix it with the URL. It's important that the data to be hashed is at least 128 bits — and this will accomplish that.

GUIDs are not/should not be cryptographically secure so GUIDs generated using this function should not be used for secure tokens. Use openssl_random_pseudo_bytes for this instead.

GUIDs are often formatted 8-4-4-4-12 but this is for readability only; the hyphens do not affect their uniqueness. Sometimes you will see GUID enclosed in { }. Again, this does not affect uniqueness — it just identifies it as a GUID. Finally, my function returns the GUID as uppercase. GUIDs are not case-sensitive since they are hexadecimal so you are free to change to lowercase.

function createGUID() { 
    
    // Create a token
    $token      = $_SERVER['HTTP_HOST'];
    $token     .= $_SERVER['REQUEST_URI'];
    $token     .= uniqid(rand(), true);
    
    // GUID is 128-bit hex
    $hash        = strtoupper(md5($token));
    
    // Create formatted GUID
    $guid        = '';
    
    // GUID format is XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX for readability    
    $guid .= substr($hash,  0,  8) . 
         '-' .
         substr($hash,  8,  4) .
         '-' .
         substr($hash, 12,  4) .
         '-' .
         substr($hash, 16,  4) .
         '-' .
         substr($hash, 20, 12);
            
    return $guid;

}

// Generate a few test codes
for($counter = 1; $counter <= 10; $counter ++) {

    echo createGUID() . '<br />';

}

The above code would output something like:

6AEB3DBF-8FAA-FFAD-5BC7-019B4456CCF8
E19B3BAA-7FD3-1D00-B6C9-5AE9C2ECB453
88BCEBC9-639B-8C42-F2A0-AD71EDB04D07
D26E94D7-237C-2E99-0CFE-5A63433CC7B2
675A096E-A909-E498-4DE4-726D5D3F6488
7B18231F-B1B7-8DD0-2323-1F4237B26302
4D6D413B-DD87-E817-0449-6F101EDCE3AC
15007730-1835-0DF3-35E8-FE17247F8967
47BF3D18-4489-437F-87DF-1CA12CF5D119
58D5CB42-E351-9976-C8A1-F3E66A751814
Tim Bennett is a Leeds-based web designer from Yorkshire. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.