Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short unique id in php

I want to create a unique id but uniqid() is giving something like '492607b0ee414'. What i would like is something similar to what tinyurl gives: '64k8ra'. The shorter, the better. The only requirements are that it should not have an obvious order and that it should look prettier than a seemingly random sequence of numbers. Letters are preferred over numbers and ideally it would not be mixed case. As the number of entries will not be that many (up to 10000 or so) the risk of collision isn't a huge factor.

Any suggestions appreciated.

like image 723
Antti Avatar asked Nov 21 '08 01:11

Antti


People also ask

How can you generate a unique ID in PHP?

A unique user ID can be created in PHP using the uniqid () function. This function has two parameters you can set. The first is the prefix, which is what will be appended to the beginning of each ID. The second is more_entropy.


1 Answers

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'))); 
like image 148
lpfavreau Avatar answered Sep 21 '22 21:09

lpfavreau