Over the past year I’ve done a lot of PHP work for organizations (*not for pay*) and this is a bit of sample code I came up with to solve their internal problem of coming up with a unique identifier for many purposes… this code is invoked withrequire "get_random_short_code.php"; where the short code needs to be set. This is intended to connect to an existing database that’s shared with an existing set of short codes. This code is far from perfect (security wise) and could be done in fewer lines, however this seems to do the trick for them…
/* Last edited Oct 29/09: 9:01p */ ##make database connection in requiring code ##the following makes sure that the shortcode for the new url is unique $isUniqueShortCode = false; ##start with 1 character short codes if database is fairly empty, add more. $rndm_len = 1; $totalTries = 0; ## the $maxTotalTries var is used to state how many tries this loop will do before moving to add another char to the short code $maxTotalTries = 40; while ($isUniqueShortCode == false){ $shortened = random_generator($rndm_len); $result=mysql_query("SELECT * FROM urls WHERE shortnened LIKE '$shortened'") or die("A BAD QUERY! ---- new_url.php"); if (mysql_num_rows($result) == 0){ $isUniqueShortCode = true; } if ($totalTries == $maxTotalTries){ $rndm_len++; ##add one to the len of the short code $maxTotalTries = $maxTotalTries+40; ##set the point when it will add another char to the short code } $totalTries++; ##run with each loop } echo "URL tries: " . $totalTries . " \n"; return $shortened; function random_generator($digits){ srand ((double) microtime() * 10000000); $input = array ( "A", "B", "C", "D", "E","F","G","H","I","J","K","L","M","N","O","P","Q", "R", "S","T","U","V","W","X","Y","Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "m", "n", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" ); $random_generator=""; for($i=1;$i<$digits+1;$i++){ if(rand(1,2) == 1){ $rand_index = array_rand($input); $random_generator .=$input[$rand_index]; }else{ // Add one numeric digit between 1 and 10 $random_generator .=rand(0,9); } } return $random_generator; } ?>
This code is free for anyone’s use with attribution; if you have any code modifications that you think would be valuable to the future of this code please comment or contact me.