How to create URL shortener using PHP

by Jeyaganesh on August 28, 2010

Basics

URL shortening is a technique in which a lengthy URL  may be made substantially shorter.

Example

http://en.wikipedia.org/w/index.php?title=TinyURL&diff=283621022&oldid=283308287

can be shortened to   http://tinyurl.com/mmw6lb

URL shortening is useful in many cases like twitter you can use 140 characters,so lengthy URLs can be shared when they are shortened.Another use is that shortened url is easier to share rather than long URLs.

There are different methods to shorten the URL,very basic method is to Http redirect to a domain that contains shortened URL.

Here we are going to see how to develop a URL shortener using PHP using http redirect.

Concept

The concept that lies behind this URL shortener is to shrink the lengthy url to small random string of characters,this can be achieved by applying some PHP functions to the lengthy URL.

php-url-shortener

php-url-shortener

here the lengthy URL string is converted to some four letter words called Key .similarly when the shortened URL is clicked,it should point to the original lengthy URL page.

php url shortener

php url shortener

Base function

First we have to generate random characters(Key) for redirection.The key may base36 ,that contains  26 alphabets and 10 numbers and we can use any hash function to generate key,I have used base_convert function to generate the Key.

string base_convert ( string $number , int $frombase , int $tobase )

The base_convert() function converts a number from one base to another.we convert to base36 format.

Files

php url shortener

index.php – The home page of Shortener,User provides long url

shorten.php – Gets the long URL from index.php and shrinks it

.htaccess – When a shortened URL is clicked ,this file gets the clicked URL and sends to decoder.php

decoder.php – decodes the shortened URL and redirects to correct page

Database structure

database structure php shortener

This is the database structure which we use to store the data.

ID field is a random 5 digit number

Url field contains the lengthy URL address

shortened field contains the key value corresponding to the unique id

Every time a URL is shortened,the url,key,a random number is inserted into the table.Vice versa if a shortened url is clicked the decode.php will fetch the corresponding url from the table using the unique key

index.php

Url:

shorten.php

< ?php

$con = mysql_connect("localhost","username","password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("DB NAME", $con); //Replace with your MySQL DB Name
$urlinput=mysql_real_escape_string($_POST['url']);
$id=rand(10000,99999);
$shorturl=base_convert($id,20,36);
$sql = "insert into TABLE NAME values('$id','$urlinput','$shorturl')";
mysql_query($sql,$con);
echo "Shortened url is http://devlup.com/". $shorturl ."";
mysql_close($con);
?>

.htaccess

Options +FollowSymLinks -Indexes -MultiViews
RewriteEngine on
#
# Internally rewrite shortened URL requests to de-shortened URL lookup script filepath plus query string
RewriteRule ^([\w\d]{4})$ decoder.php?decode=$1 [L]

decoder.php

< ?php

$con = mysql_connect("localhost","username","password");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
mysql_select_db("DB NAME", $con); //Replace with your MySQL DB Name

$de= mysql_real_escape_string($_GET["decode"]);

$sql = 'select * from TABLE NAME where shortened="$de"';

$result=mysql_query("select * from TABLE NAME where shortened='$de'");

while($row = mysql_fetch_array($result))
{
$res=$row['url'];
header("location:".$res);
}
?>

Demo

http://projects.devlup.com/url/

Download

http://www.box.net/shared/u4ryl4gv6e

Related posts:

Develop Facebook app using PHP in 10 minutes
Spring Savings! $7.49 .com domain
Free iPhone Programming Ebook
How smart is your Theme?  How good is your support? Check out ThesisTheme for WordPress.

{ 25 comments… read them below or add one }

Mohamed Raja August 29, 2010 at 7:32 pm

Good tutorial…..need some explanation abt .htaccess file

Reply

Sean O August 29, 2010 at 10:49 pm

Nice, simple technique.

For an alternative method, using simple 404 pages, and don’t want to mess with .htaccess, try my tutorial:

http://sean-o.com/short-URL

Reply

RaajeshAdam August 29, 2010 at 11:15 pm

Thank you…very much. Great..yaar

Reply

ask September 12, 2010 at 1:04 am

It’s really a very good read about

Reply

movs September 30, 2010 at 8:50 pm

Thanks !
Me and my friends we use http://stito.net/ !

Reply

Phani October 22, 2010 at 2:37 pm

There is a small bug..after clicking the shortened url the page goes in this way

http://www.mysite.com/google.com

where the google.com is shortened earlier.

hw to overccome this porblem

Reply

Jeyaganesh October 23, 2010 at 11:48 pm

Once you have placed the files in your server please change the “mysite” to yoursite name.
Make sure that .htaccess file is placed in same folder.

If this doesn’t resolve your problem. please reply back.

Thanks for the feedback phani :-)

Reply

Jeyaganesh October 23, 2010 at 11:51 pm

also make sure http:// is included before the url.

Reply

Jacob Goedicke December 16, 2010 at 11:02 pm

Wow! Thank you! I constantly wanted to write on my site something like that.

Reply

The Diet Solution December 20, 2010 at 8:50 am

Apreciate the info, many thanks!

Reply

Brett Widmann January 17, 2011 at 12:32 am

This is just what I was looking for! Thanks for the help.

Reply

Anees February 25, 2011 at 6:18 pm

My webhost doesn’t support .htaccess redirection. How can I do that with php itself?

Reply

Jeyaganesh February 26, 2011 at 5:33 pm

If u dont have .htaccess redirection. In php you can redirect the page using
header(‘Location: ‘NEWURL’);

Reply

dan April 9, 2011 at 1:15 am

Hi. I tried your code and when I hit shorten url I get a page back of the decoder or shortener php file?

Is it something to do with .htaccess or apache.
Why would it show the whole php code page?

Thanks,
Dan

Reply

Jeyaganesh April 9, 2011 at 1:42 am

Hi dan

Do you have local server running? I dont think the page pack will get displayed if the server is running fine.

Reply

Tyler June 18, 2011 at 9:06 pm

to do the redirect in PHP:

If you’re getting just the PHP code when you hit the URL shortener, chances are you webserver/host is unable to process .php files. Check to make sure you have PHP installed.

Reply

Tyler June 18, 2011 at 9:06 pm

Bah my code didnt work
To do the redirect in PHP

header(“Location: “. $res);
exit();

:)

Reply

Jeyaganesh June 18, 2011 at 9:37 pm

Thanks Tyler.

Reply

c0mma July 11, 2011 at 11:14 am

When I shorten the url, go to the url, it says; Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/c0mmanet/public_html/url/decoder.php on line 19

http://url.c0mma.net/ipgi

Reply

c0mma July 11, 2011 at 11:45 am

Forget it, i got it working ;D http://url.c0mma.net – take a look ;D

Reply

Rob October 18, 2011 at 8:51 pm

I have implemented this all and I can write to the DB with shorten.php but when I put the shorted URL in I get:

Not Found

The requested URL /ltxh was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

Apache/1.3.42 Server at sendnow.co Port 80

Any ideas on why?

Reply

Jeyaganesh October 18, 2011 at 10:40 pm

Rob,

There was a typo in the code,Now I have corrected it.Please download the code and try again.

Thanks.

Reply

Eric December 8, 2011 at 10:20 pm

How can you make the key longer than 4 characters ei up to 5 or 6

Reply

Jeyaganesh December 10, 2011 at 12:15 pm

It depends on base-convert function and the number of digits you specify in the rand() function. Thanks.

Reply

Mike January 17, 2012 at 3:15 pm

Why is this using an random integer for the database id, shouldn’t the database decide on that? What if they clash? It’s not checking if it exists before attempting to use it, and anyway, why not just have SQL auto increment the ID? If you need to know the id for the encryption, (not that that’s a good idea), but you’d use mysql_insert_id(); to find out what auto increment value the database used.

Every part of your tutorial is really amateur coding, you should probably have mentioned that in your post somewhere, before others learn anything from it.

Reply

Leave a Comment

{ 1 trackback }

Previous post:

Next post: