Generating a UUID in PHP

Posted: September 25th, 2010 | Author: Laurie | Filed under: Uncategorized | No Comments »

We need to generate UUIDs in PHP. This is actually extremely easy: there is a PHP UUID package in PECL, but you’d never know, because there’s no documentation, a problem that’s apparently been the case forever — a documentation bug was opened in 2006, but never resolved, even though there is some documentation in the source code.

Even more simply, in ubuntu there is a package called php5-uuid. It can be installed just with

apt-get install php5-uuid

However, documentation is even more sparse for this one — the best that exists appears to be a comment on the PHP manual page for uniqid() (of course, if all you need is a unique ID, that function is probably easier still, but we needed a UUID specifically). Anyway, the magic code to create a UUID is simply this:


uuid_create(&$v4);
uuid_make($v4, UUID_MAKE_V4);
uuid_export($v4, UUID_FMT_STR, &$v4String);
echo "My UUID is now in $v4string";

This is obviously a version 4 UUID; you can trivially make the others just by changing the arguments appropriately. Wikipedia has a good page explaining the difference between UUID versions.


Comments are closed.