How to create URL shortener using PHP

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:

About Jeyaganesh

I am Jeyaganesh,Information Technology graduate from India.Interested in web designing, PHP, wordpress and Graphic designing. Love to play with all kind of new technologies in Web.Follow me on twitter and Connect with Google+

Comments

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

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

  3. Thank you…very much. Great..yaar

  4. It’s really a very good read about

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

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

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

  8. Apreciate the info, many thanks!

  9. This is just what I was looking for! Thanks for the help.
    Brett Widmann recently posted..The History and Present State of Domain Names Infographic

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

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

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

  13. Bah my code didnt work
    To do the redirect in PHP

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

    :)

  14. Thanks Tyler.

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

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

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

  18. Rob,

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

    Thanks.

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

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

  21. Hello! Thanks for this script! But there is a problem: when i’m pressing “short” it’s only shows me a text of shorten.php. What is wrong?
    P.s. Can you give me a code of mysql table for this script, please?

  22. Generating an ID based on a random number could easily created two IDs that are the same.

  23. Nice script but two suggestions:

    1) You might want to do some validation on the long URL to make sure the user didn’t forget http:// or that it doesn’t get a 404 error.

    2) I ran a simple script that generated 1,000 shortened URLs using this method and got at least 3 or 4 duplicates every time I ran it. You might want to create a function to ensure the generated shorturl is unique in the database otherwise you’re going to run into some problems.

    Good job otherwise…thanks for the post!

  24. When ever I click the shortened URL I get this error:

    Parse error: syntax error, unexpected ‘{‘ in /var/www/vhosts/awesomethings.net.nz/httpdocs/phpshortner/decoder.php on line 17

    And this is line 17:

    {

  25. Positive, I ve triple checked it. It still doesnt work.

  26. You can Enable Rewrite option from httpd.conf from wamp. Then make sure following code could be uncommented.
    LoadModule rewrite_module modules/mod_rewrite.so

  27. aLdyputRa says:

    Nice,,
    A Simple Technique..

    Good Job..

  28. Wira Intruder says:

    Hi, Thanks for this nice script.
    But I get little problem in here, why I always get 404 error page?

    I have edited all MySQL config to match my server config.

    Any suggestion?

  29. I keep getting 404′s
    I then found when I went to my “decoder.php” page that I got this error

    “Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource”

    Any way to fix it?

  30. I have this working – loving it, Thanks!

    I added a 404 error page (and adding ErrorDocument 404 /error.php to my .htaccess files) to catch any errors – this works fine if there are fewer than or more than 4 letters/numbers in the short url. If there are 4 then the browser is blank.

    I gather this is something to do with the decoder.php file. Is there any way of checking to see if the short url code exists, and if it doesn’t then redirect to the error.php page?

    Thanks!

  31. thanks for d script. But I have done everything ypu asked us to. But when i input a url and click shorten. It brings out a custom shortened url. But when i click d shortened url it shows a blank page. Pls any means on hw i can solve this. And that base convert. I dont know how to use it. Pls can u shed m0re light on it.

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

    i dnt understand that. I guess that where d problem is from. Pls reply thanks

  32. I need help making the sql file i do not know what to add or make for the settings

Trackbacks

  1. [...] at this time.  Edward Yu, Student, Programmer There's a very good tutorial here: http://devlup.com/programming/ph…This answer .Please specify the necessary improvements. Edit Link Text Show answer summary [...]

Speak Your Mind

*

CommentLuv badge