Generate UUID in PHP

23Feb

I posted this last year to PHP.net and thought I’d just share it here as well. It’s a short write-up and demonstration of a PHP class you can use to generate various versions of a Universally-Unique Identifier, or UUID.

The uuid_make() function takes two arguments when generating v1 or v4, but four arguments are required when generating v3 or v5. The first two arguments have been thoroughly demonstrated and are straightforward, so I’ll skip to the as-yet non-described arguments.

The third argument to uuid_make() is: $namespace
– this is a secondary resource created with uuid_create(); it is apparently used to generate an internal UUID, which is used as the namespace of the output UUID

The fourth argument to uuid_make() is: $url
– this is the value that is to be hashed (MD5 for v3, SHA-1 for v5); it may be any string or even null

Here’s a simple class illustrating the proper usage (note that if php5-uuid is not installed on your system, each function call will just return false):

As you can see, the calls to v3() always return the same UUID because the same URL parameter, “abc”, is always supplied. The same goes for the v5() function which is always supplied a null URL.

The v4() UUIDs are always entirely different because they are (pseudo)random. And the v1() calls are very similar but just slightly different because it’s based on the computer’s MAC address and the current time.

I have updated the code to include variable declarations and to remove the pass-by-reference ampersands from the function arguments, and that will resolve the “deprecated” warning in PHP 5.3 (which is an error in PHP 5.4).