Sunday, July 14, 2013

Creating own URL Shortner

Well, we have seen many websites like bit.ly, goo.gl, and also the $$ earning adfoc.us and adf.ly. Ever wondered how these systems work?
Well, I don't know how exactly do they work, but I can show you how to create something like those websites.
The concepts that we will be using to create own URL shortner are: MySQL access functions in PHP, and the header function in also, PHP.

First we need to set up a MySQL database containing two columns more importantly. Here is the SQL query for the same
CREATE TABLE shorturls
(
short_url varchar(6),
long_url varchar(256),
);

Now, we have a table with two columns with the list of the short URL codes and the corresponding long URL. For this instance, I will be using the URL code "tekish" and it will point to http://techieanish.blogspot.com. Don't worry, we will be talking about generalizing the data. That is every time a URL code is gonna fire, it will redirect to corresponding long URL. So, now as we are done with creating tables, we are now gonna set up the PHP script that will fire when you visit the code. For this, first we will need to do some nice good setting. As we are just dealing with the basic concepts, the sweetness of this desert will be the 404 redirect. To do this, follow these steps:
  1. If you are using Apache as your server, save a file called ".htaccess" in the main directory of your website. The directory in which your index.php lies.
  2. Now, in this directory, enter the following: ErrorDocument 404 /redirect.php
Now we are going are going to write the code for redirect.php. Well, we did the htaccess thing so that whenever some random piece of string goes behind your web domain name, a 404 error occurs. Now, to show that 404 error, we fire up the redirect.php, that is basically a redirecting PHP script.
Now lets do the real thing. Code redirect.php

Basic notes and additional tips:

  •  In handling the .htaccess file, make sure your correctly enter the address of the location of your redirection script. Make sure you enter the path as on server, not as your local domain.
  • There are lot of things I haven't included in the script, which include analytics, form to create new URLs, and an error page if the code is not found. Explore them on your own! 
  • Well, when you are starting a service, you will obviously need to set up a random code generator for new URLs. Here is a small example on how you can create random alphanumeric codes that can be used as your short URLs.
  • Also, trim the URL you get to alphanumeric code for security
  • Got more tips? Share them in comments.
More coding at Let's Code!


No comments:

Post a Comment