How to create URL shortener using PHP

By

August 28, 2010PHP45 Comments

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

45 Responses to “How to create URL shortener using PHP”
  1. Mohamed Raja

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

  2. Sean O

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

    Thank you…very much. Great..yaar

  4. ask

    It’s really a very good read about

  5. movs

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

  6. Phani

    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

    • Jeyaganesh

      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 🙂

    • Jeyaganesh

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

  7. Jacob Goedicke

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

  8. The Diet Solution

    Apreciate the info, many thanks!

  9. Brett Widmann

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

  10. Anees

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

    • Jeyaganesh

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

  11. dan

    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

    • Jeyaganesh

      Hi dan

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

  12. Tyler

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

    Bah my code didnt work
    To do the redirect in PHP

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

    🙂

  14. Jeyaganesh

    Thanks Tyler.

  15. c0mma

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

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

    • mathechr

      How did you get it to work? I’m getting the same error….

  17. Rob

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

    Rob,

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

    Thanks.

  19. Eric

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

    • Jeyaganesh

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

  20. Mike

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

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

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

    • Jeyaganesh

      I agree Chris,this could be a good tutorial for php beginners.

  23. Tony P

    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!

    • Jeyaganesh

      Thanks Tony for pointing out the errors.

  24. Jayden

    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:

    {

    • Jeyaganesh

      Jayden,

      Have you missed any ‘(‘ ? please check the 17th line.

  25. Jayden

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

  26. Kedar

    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

    Nice,,
    A Simple Technique..

    Good Job..

  28. Wira Intruder

    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?

    • Jeyaganesh

      Hi,

      Is the URL which you are shortening is a valid page ?

  29. Mr407

    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?

    • Jeyaganesh

      Hi,

      Can you check your query ? might be some extra quotation or syntax error might cause this. You can also check on phpmyadmin sql query window.

  30. Neill

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

    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

    • Jeyaganesh

      Please provide more details.The shortened URL should have a domain name on which the .Htaccess file should be configured.

  32. Corbin

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

  33. Ahmed

    i didn’t understood how the decoder page work ;
    $_GET[“decode”] ???
    and what this .htaccess ??

Leave a Reply

*