Hey all I'm putting a URL shortening website together and I just wondered if anyone knows how to generate alpha-numeric links, rather than just numeric? For example, I know how to create numeric ones as follows: website.com/123 That's easy. But what I want is the kind of alpha-numeric links you get from bit.ly and tinyurl: website.com/5fj8i I've tried searching for a script but I can't find one that meets all my criteria - the closest match does everything else I want it to, but not the alpha-numeric thing. If anyone can give me any help/advice I'd really appreciate it Thanks for your time Adam
Try this: function random_string($length=16) { $string = ''; $possible = "0123456789abcdefghijklmnopqrstuvwxyz"; for($i=1;$i<$length;$i++): $char = substr($possible, mt_rand(0, strlen($possible)-1), 1); $string .= $char; endfor; return $string; } PHP: You will want to store url's in a database and check to make sure one doesn't exist before using it. Change the default length to whatever you want, or just call it with a specified length.
why not using a random alpha-numeric string generator function? just like password generators, if you search, there are lots of scripts around.
I've got the random string generation sussed, thanks to jestep. Now I just need to figure out the most efficient way of creating a unique string each time, as each string that is generated is inserted into the database and must be unique. Bit of a headache!
This should be easier and more efficient: $lengthOfString = 4; $randomString = substr(md5(uniqid(rand(),1)),1,$lengthOfString); echo $randomString; PHP:
Not sure what your DB name or columns are but try this. $new_url = random_string(); function random_string($length=16) { $string = ''; $possible = "0123456789abcdefghijklmnopqrstuvwxyz"; for($i=1;$i<$length;$i++): $char = substr($possible, mt_rand(0, strlen($possible)-1), 1); $string .= $char; endfor; $query = mysql_query("SELECT id FROM my_table WHERE url = ".$string.""); if(mysql_num_rows($query) > 0) { random_string($length); } return $string; } PHP: You'll need to adjust the query to fit your db, but this will reiterate the function until a unique url is created.
I would suggest that you use base_convert(). Consider the following: The visitor goes to yoursite.com/5fj8i Your server rewrites yoursite.com/5fj8i into yoursite.com/redirect.php?id=5fj8i With the help of base_convert(), your script converts 5fj8i (which is base 36) into 9122850 (which is base 10) You retrieve the URL from database row with the id 9122850 and redirect the visitor This is the way I've done it before and it makes the process a lot easier with no need for storing any random unique alphanumeric strings.