Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.
Rick Osborne

Very Simple URL Shortener

This past few days I have seen a trend of shorting URL in (me & my friend)’s Plurk. Then it struck me, why don’t we create our owns? I have seen many URL shortener website, like u.nu, bit.ly, adf.ly, de.tk, kom.ps, tinyurl.com, etcetcetc… And I also have seen some PHP source code to create one of these. Well, just out of curiosity I want to create one from scratch.

So what do we need? A storage for all URLs and their keys. Since this is just a simple URL shortener (input: 1 URL, output: 1 short URL), I use just one table:

CREATE TABLE IF NOT EXISTS `data` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `key` varchar(100) NOT NULL,
  `url` text NOT NULL,
  `visit` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `key` (`key`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1;

‘id’ column is the primary key, ‘key’ column is the unique identifier of URL much like “dGouHS” in http://bit.ly/dGouHS, ‘url’ column is the originial URL, and ‘visit’ column simply stores how many times the short URL visited.

How does the app works? To keep it simple, I break down the app into many functions so that the “main program” is readable, like this:

// The "main program", the code literally explains itself
startup();
if (is_requesting_url()) {
	if (is_key_exist()) {
		redirect_to_url();
	} else {
		display_page_with_error();
	}
} else if (is_submitting_url()) {
	if (is_url_valid()) {
		display_page_with_result();
	} else {
		display_page_with_error();
	}
} else {
	display_page();
}
shutdown();

Read the rest of this entry »

February 21st, 2011 PHP Tags: , , , 0 Comment 1,053 views