Generating UUIDs with CakePHP

Published on and tagged with cakephp  feature

Some months ago I presented in “UUID component for CakePHP” a simple component to generate UUIDs (Universally Unique Identifiers). With changeset 5552, this component has become obsolete, at least if you are using CakePHP 1.2. The new introduced class “String” provides an easy way to generate UUIDs:

$uuid = String::uuid();

This function can be used anywhere, without including anything.

7 comments baked

  • Abhimanyu Grover

    Nice and handy.. Thanks :)

  • Yevgeny Tomenko

    @cakebaker: I have one question. May be you know that in rails exists plugin that make same thing for ror projects(
    But it manipulate with 22 length url sage uuid instead of 36 bytes as in cake. So why 22 buty is more url safe than 36?

  • cakebaker

    @Yevgeny: I’m sorry, but I don’t know the answer to your question… It’s the first time I hear about this 22 character format ;-)

  • PD

    @Yevgeny: It’s not that the 36-char format isn’t URL safe; it’s all ascii letters, numbers, & dashes, so it’s inherently URL safe. It’s just long.

    The 22-char format comes from running a few operations on it. First, you do a quick str_replace to pull the “-“‘s out. They’re always in the same place, so why have them there?

    Then, you can run “pack(‘H*’,$string)” on the thing, where $string is the result of the str_replace. That will code the ASCII down to a much shorter binary value. However, that binary is most definitely *not* URL safe; it’s binary.

    So, you do a base64_encode on the thing. That results in a new ASCII string, 24 characters in length. The last two characters will always be “==” padding, however, because of the size of the binary you get from pack().

    Finally, you can get 22 characters by rtrimming those ‘=’ chars out.

    All in all, looks kinda like rtrim(base64_encode(pack(‘H*’,r(‘-‘,”,$uuid))),’=’)
    where $uuid is your original 36-char uuid.

    None of those opperations are lossy, so you can always reverse back and get the same UUID again:
    unpack(‘H*’, base64_decode($shortuuid . ‘==’))
    will give you back the original UUID, but without the dashes. It’s easy enough to put those back in, by chunking that string into groups of 4, and combining the first 2 and last 3 elements of the array, and joining that result with dashes. Or maybe a quick preg_replace.

  • cakebaker

    @PD: Thanks for your explanations!

  • Peter


    Do you know how YouTube is getting their unique id?
    More hash??

    Any help would be appreciated. Thanks.

  • cakebaker

    @Peter: It looks like they use a hash function to generate such IDs, but I don’t know which hash function they actually use…

© daniel hofstetter. Licensed under a Creative Commons License