Wednesday, April 6, 2011

Tiny URL generating source code - PHP

Hi,

Tiny URL's are very popular when it comes to shortening a web URL. There are many third party tools such as bit.ly, tinyurl.com etc. But if you want to do it yourself, then you will find the entire source code and the logic of how it works in this post.

For this you need to keep in mind the following:
1. Providing an interface to the user to enter any URL and on submitting it a short URL is generated. The domain of the short URL will be in your server.
e.g.
if your website name is http://tiny.url, then the tiny urls should look something like, http://tiny.url/#####. Where "#####" is a tinyword which represent the actual URL which the user has entered.

2. You need to convert the above http://tiny.url/##### into its corresponding URL and redirect the page to there.

In my case instead of http://tiny.url/##### I will be using http://localhost/php/tinyurl/######, since I am running from my localhost. So lets start with the development.

Code and Explanation:
First lets create a interface to let the users enter any URL as follows:


For the above, I have added a "p/" in the URL just to seperate a normal page in my website from the short URL pattern, else it would have treated "shortenurl" as a short form of an URL and try to redirect it. When the user submits the URL, first it checks whether this URL has been submitted before or not by:


$exist=mysql_fetch_array(mysql_query("select * from tinyurls where actualurl='".$_POST['url']."'"));
if(empty($exist))
{
// code to generate the tiny word representing the actual URL
}else{
$tiny_word=$exist['shorturl'];
}

Now if the URL has not been submitted before this is what I am doing:

if(empty($exist))
{
function get_random_word($length=6){
                      // code to generate a random unique 6 letter word.
}
$tiny_word="";
while($tiny_word==""){
$tiny_word=get_random_word();
}
mysql_query("insert into tinyurls set shorturl='".$tiny_word."', actualurl='".$_POST['url']."'");

}
Now a new 6 letter random word and the actual URL is stored in the database in a mapping table. After saving in database, it just displays the shorten URL as follows:



Now 50% of our job is done. Now we need to write the code, which will redirect the above generate tiny URL (i.e. http://localhost/php/tinyurl/egIx6T) to its actual website. First we need a ".htaccess" file in the root directory with the following content:
<IfModule mod_rewrite.c>
   RewriteEngine on
   RewriteRule    ^p\/(.*)$ page.php?q=$1 [L]        // checking for some internal pages of the website
   RewriteCond %{REQUEST_FILENAME} !-d   // checking for non internal page of the website
   RewriteCond %{REQUEST_FILENAME} !-f   //  for tiny URL
   RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]   // and redirecting to the index.php with the tiny word as parameter
</IfModule>

Now in index.php we need the following:
$url=$_GET['url'];   // fetch the tiny word which is mapped with the actual URL in database
$url_details=mysql_fetch_array(mysql_query("select * from tinyurls where shorturl like ('".$url."')"));
if(!empty($url_details)){
header("location: ".$url_details['actualurl']);   // redirect to actual URL if valid tinyword
}else{
echo '<h2 style="color:red">Error 404: Page not found</h2>';   // displaying error if invalid tinyword
}

For full source code with database download: tinyurl.zip

You just need to make 1 change in page.php. You will see a line:
echo "TinyURL: http://".$_SERVER['SERVER_NAME']."/php/tinyurl/".$tiny_word."<br/><br/>";

You need to change the path "/php/tinyurl/" according to your needs. For live server it will be replaced by just "/"  i.e.
echo "TinyURL: http://".$_SERVER['SERVER_NAME']."/".$tiny_word."<br/><br/>";

That's All :)


No comments:

Post a Comment