I wrote this function in order to create unique url's for my site. Using these urls, visitors could demo site functionality without having to create a login. The function was intended to return a unique string of characters which could be added to a url like this:
http://www.mysite.com?temp_user=dd5vbrk4ax4v4o09l2bm
My function had the following criteria:
- Every call must generate a unique string of alpha numeric characters.
- Most important: Zero chance of string duplication.
- It should be 20 characters long (secure, but not awkwardly long.)
- Repeat calls should reflect a high degree of dissimilarity.
- Character usage should appear as random as possible.
Here is my code
function url_code(){
$letters = "1234567890abcdefghijklmnopqrstuvwxyz";
$microtime = microtime();
$time_array = explode(' ', substr($microtime,2));
$code = '';
$time_array[0] = substr($time_array[0],0,6);
$time_array[0] .= strrev($time_array[0]);
$time_array[2] = strrev($time_array[1]);
for($i = 0; $i <10; $i++){
$num = ((int)$time_array[1][$i]);
$num += ((int)$time_array[2][$i])*10;
$num += ((int)$time_array[0][$i])*100;
$mult = (int)($num / 36);
$mod = $num - ($mult * 36);
$code .= $letters[$mult].$letters[$mod];
}
return $code;
}
Please let me know if there are any simple improvements I could make or if I missed any serious problems with string repetition.
One interesting note on character randomness: currently, characters generated by the $mult variable (the first, third, fifth, and other odd character in the code string) will never be t,u,v,w,x,y, or z. How can I fix this so that [t-z] are also used?
Possible fix (all characters will be used. However, [8-9a-s] are twice as likely to appear as the other characters, [0-7t-z]):
$mult = (int)($num / 36);
$mod = $num - ($mult * 36);
if($mult < 9 && mt_rand(0,1)){$mult += 27;}
$code .= $letters[$mult].$letters[$mod];
Note, Scalability issue found: If this function is run on more than one server, there is a tiny chance that two users could send a request at exactly the same time and get a duplicated code.