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.
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.
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
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
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
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







{ 25 comments… read them below or add one }
Good tutorial…..need some explanation abt .htaccess file
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
Thank you…very much. Great..yaar
It’s really a very good read about
Thanks !
Me and my friends we use http://stito.net/ !
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
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
also make sure http:// is included before the url.
Wow! Thank you! I constantly wanted to write on my site something like that.
Apreciate the info, many thanks!
This is just what I was looking for! Thanks for the help.
My webhost doesn’t support .htaccess redirection. How can I do that with php itself?
If u dont have .htaccess redirection. In php you can redirect the page using
header(‘Location: ‘NEWURL’);
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
Hi dan
Do you have local server running? I dont think the page pack will get displayed if the server is running fine.
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.
Bah my code didnt work
To do the redirect in PHP
header(“Location: “. $res);
exit();
Thanks Tyler.
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
Forget it, i got it working ;D http://url.c0mma.net – take a look ;D
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?
Rob,
There was a typo in the code,Now I have corrected it.Please download the code and try again.
Thanks.
How can you make the key longer than 4 characters ei up to 5 or 6
It depends on base-convert function and the number of digits you specify in the rand() function. Thanks.
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.
{ 1 trackback }