Posted by & filed under Programming.

During development of an online application, I needed a way to generate a GUID. I’m sure there are other, better ways to do this. But, this is how I decided to do it.

Originally, I looked at looping through with a random character routine to whatever length I needed. But, being the obsessive person that I am, I decided to test it first. So, I wrote a routine in Visual Basic that looped through creating 10 character codes and seeing if the code it just created matched the first one. The first time it ran it matched after about 50,000 tries. The second time was at about try 200. So, obviously this wasn’t random enough. Windows has a function built into the API to create GUIDs, so I figured maybe PHP has the same.

Turns out, it does. The function is uniqid. This function uses the server clock to generate a unique string based on the microsecond. So, unless you generate two in the same 1,000th of a second, you’re ok. I decided to append the remote IP address (without periods) to the front to make it even more random. This way, even if two codes are generated in the same microsecond, they will still be different.

function CreateGUID()
/*  CreateGUID is used to return a unique ID to use as an index
    in the database.  It is a maximum length string of 35.  It uses
    the PHP command uniqid to create a 23 character string appended
    to the IP address of the client without periods.                */
    //Append the IP address w/o periods to the front of the unique ID
    $varGUID = str_replace('.', '', uniqid($_SERVER['REMOTE_ADDR'], TRUE));

    //Return the GUID as the function value
    return $varGUID;

2 Responses to “A routine to create GUIDs in PHP”

Leave a Reply

Your email address will not be published. Required fields are marked *