A routine to create GUIDs in PHP

Posted in Programming  
E-Mail This Post/Page   

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.

PHP:
  1. function CreateGUID()
  2. /*  CreateGUID is used to return a unique ID to use as an index
  3.     in the database.  It is a maximum length string of 35.  It uses
  4.     the PHP command uniqid to create a 23 character string appended
  5.     to the IP address of the client without periods.                */
  6.     {
  7.     //Append the IP address w/o periods to the front of the unique ID
  8.     $varGUID = str_replace('.', '', uniqid($_SERVER['REMOTE_ADDR'], TRUE));
  9.    
  10.     //Return the GUID as the function value
  11.     return $varGUID;
  12.     }

500 hours + MS Paint = ?
A quick function to back up MySQL databases
PHP: A function to return the first n words from a string
Found a trick in Eventum - Autolinking issues
RAID array out of iPods

Leave a Comment