Shortening URLs: Decoding & Encoding

28 Sep 2010 by admin, Comments Off

One of the things I needed to make for this project was a URL shortener. Sure I could have used one of the existing services but then people wouldn’t know it’s from this domain. I think there’s value in using shortened URLs from your own site.

This is the PHP code I use to convert tweetdonate.org/2AD3 into a link stored in the database, update the click count for that link and then send the user’s browser to the right location:
$key = $_GET['key'];
$ID = (int)base_convert($key,36,10);
$result = mysql_query('SELECT url FROM ShortenedLinks WHERE ID = '.$ID.' LIMIT 1');
if(mysql_num_rows($result)>0){
$result = mysql_fetch_assoc($result);
mysql_query('UPDATE ShortenedLinks SET click_count=click_count + 1 WHERE ID = '.$ID.' LIMIT 1');
header('Location:'.$result['url']);
}else
echo "This URL is no longer valid (if it ever was).";

How do you make the links? That’s even easier:
define('SHORTENED_URL_LINK_TEMPLATE','www.tweetdonate.org/%s');

function shortened_link_create($url){
if(mysql_query('INSERT INTO ShortenedLinks(url) VALUES(\''.$url.'\')'))
return sprintf(SHORTENED_URL_LINK_TEMPLATE,base_convert(mysql_insert_ID(),10,36));
return false;
}

Comments are closed.

Follow Me!

Follow Me! Follow Me! Follow Me! Follow Me!

Recent Actions