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:

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.