Short unique id in php

@gen_uuid() by gord.

preg_replace got some nasty utf-8 problems, which causes the uid somtimes to contain "+" or "/". To get around this, you have to explicitly make the pattern utf-8

function gen_uuid($len=8) {

    $hex = md5("yourSaltHere" . uniqid("", true));

    $pack = pack('H*', $hex);
    $tmp =  base64_encode($pack);

    $uid = preg_replace("#(*UTF8)[^A-Za-z0-9]#", "", $tmp);

    $len = max(4, min(128, $len));

    while (strlen($uid) < $len)
        $uid .= gen_uuid(22);

    return substr($uid, 0, $len);
}

Took me quite a while to find that, perhaps it's saves somebody else a headache


Make a small function that returns random letters for a given length:

<?php
function generate_random_letters($length) {
    $random = '';
    for ($i = 0; $i < $length; $i++) {
        $random .= chr(rand(ord('a'), ord('z')));
    }
    return $random;
}

Then you'll want to call that until it's unique, in pseudo-code depending on where you'd store that information:

do {
    $unique = generate_random_letters(6);
} while (is_in_table($unique));
add_to_table($unique);

You might also want to make sure the letters do not form a word in a dictionnary. May it be the whole english dictionnary or just a bad-word dictionnary to avoid things a customer would find of bad-taste.

EDIT: I would also add this only make sense if, as you intend to use it, it's not for a big amount of items because this could get pretty slow the more collisions you get (getting an ID already in the table). Of course, you'll want an indexed table and you'll want to tweak the number of letters in the ID to avoid collision. In this case, with 6 letters, you'd have 26^6 = 308915776 possible unique IDs (minus bad words) which should be enough for your need of 10000.

EDIT: If you want a combinations of letters and numbers you can use the following code:

$random .= rand(0, 1) ? rand(0, 9) : chr(rand(ord('a'), ord('z')));

You can achieve that with less code:

function gen_uid($l=10){
    return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyz"), 0, $l);
}

Result (examples):

  • cjnp56brdy
  • 9d5uv84zfa
  • ih162lryez
  • ri4ocf6tkj
  • xj04s83egi