Register .COM/.NET for Just $4.99 Only!!
 

HowTo: Create your own Bit.ly or Tinyurl.com Website from Scratch .

Posted by Sheriff 28 November, 2009 (0) Comment

Shortening a long address into a short one is now becoming very famous and especially in sites like twitter and blogs. I was always think that i need to deal something that is useful for people and finally decide to show you guys how to create a tiny url site like Bit.ly or Tinyurl.com

First the requirements:

If you are doing on your local machine:

You require the following
1. Apache
2. PHP
3. MySQL

or you can go for complete automation system like WAMP for Windows, MAMP for MAC and LAMP for Linux operating system.

In this whole tutorial i will be using WAMP.

If you are doing on a remote host, it should support:

1. PHP
2. MySQL
3. .HTACCESS

Coding Up:

I will not go in depth about installing the above servers but there are already lot of tutorials on this and still if you want to contribute a tutorial you can be a guest author.

I don’t want to make this post boring so i will go simple and easier for any users. I hope you are a bit familiar with PHP and mySQL and even if you are not you can download and run it but still it becomes like a copy and paste.

Phases that we develop:

1. Allowing User to add a long URL
2. Allowing user to add his own alias name
3. Validating the availability of Alias name
4. Storing the long URL into MySQL
5. Count system
6. Playing with .htaccess
7. Retrieving the long URL

Phases you can expand:
1. Log In System where register users can manage the URL’s added by them
2. Create a graph system using counts and date to let the user know visits to a particular URL

The 1st phase:

Here first let us create a MySQL database. I hope you guys know how to create a mysql data.

I will be creating the database name as “gotiny_base”  and let us Create a table called “url_tables”

These are all the fields a table must have.
Alias – Varchar[20]
URL – text
count – Integer
date – Timestamp

Here is the MySQL Code:

1.CREATE TABLE `gotiny_base`.`url_tables` (
2.`alias` VARCHAR( 20 ) NOT NULL ,
3.`url` TEXT NOT NULL ,
4.`count` INT NOT NULL ,
5.`date` TIMESTAMP NOT NULL
6.) ENGINE = InnoDB
Now MySQL work is completed now let us goe to HTML and CSS Part.

Here is the CSS code “mystyle.css”:
01.body{
02.margin:0;
03.padding:0px 0 10px;
04.background:#616E76;
05.color:#999999;
06.font-family:"Lucida Grande","Lucida Sans Unicode",sans-serif;
07.font-size:11px;
08.}
09.
10.#wrap{
11.margin:5em 10em 2em 25em;
12.width:500px;
13.}
14.
15.#box-a{
16.width:100%;
17.height:auto;
18.background:#FFFFFF;
19.-moz-border-radius: 2px;
20.-khtml-border-radius: 2px;
21.-webkit-border-radius: 2px;
22.overflow:hidden;
23.}
24.
25.#forms{
26.padding:1em;
27.}
28.
29.#formwhat{
30.clear:both;
31.color:#888888;
32.text-align:right;
33.}
34.
35.#forms input.text{
36.font-size:1.5em;
37.width:98%;
38.}
39.
40.#forms input.alias{
41.font-size:1em;
42.width:240px;
43.}
44.
45..button{
46.background:#2E5D79;
47.border-color:#DFF2FF #888888 #888888 #DFF2FF;
48.border-style:solid;
49.border-width:1px;
50.color:#FFFFFF;
51.cursor:pointer;
52.font-size:1.5em;
53.margin:0 0 0 1em;
54.padding:0.2em 8px;
55.}
56.
57..footer a{
58.color:#FFFFFF;
59.border-bottom:#FFFFFF 0.1em dotted;
60.text-decoration:none;
61.}

Now the HTML code “index.html”:

01.<div id="wrap">
02.<div id="box-a">
03.<form id="forms" method="get">
04.
05. <label>Drop your long URL
06.<input id="originalurl" class="text" name="originalurl" type="text">
07. </label>
08.
09.Pick your Alias name (OPTIONAL):
10.
11. <label></label>
12. <span class="style1">http://gotiny.co.cc/
13.<input id="alias" class="alias" name="alias" type="text">
14. </span>
15.
16. No white space and minimum 4 characters.
17.<div id="formwhat">
18.<input id="create" class="button" name="create" value="Tiny URL" type="submit"></div>
19.</form>
20.</div>
21.<div class="footer"><a href="http://">This code is written by Programmer
22.</a>| <a href="http://">Download this Code for FREE</a></div>
23.</div>
In the above html code we are using a for with digit text field one is originaltext field and another one alias. Here in originaltext a user inputs the original URL and in alias he can put his own alias name so that he can remember, but we are making this as optional so that if he leaves that field blank then we must generate a haphazard alias name
Here is the current front end view:
HowTo: Create your own Bit.ly website from Scratch Now we have finished the front end it time to work on our main system. This system will store the original URL and create an alias name.

The PHP Part:
1st the cofiguration page “config.php”:

1.$Database_Username = "username";
2.$Database_Password = "password";
3.$Database_Name = "gotiny_base";
4.$Database_Host = "localhost";
5.$DBConn = mysql_connect($Database_Host, $Database_Username, $Database_Password) or die("Unable to connect to our database server. Check your settings.");
6.$DB_DB = mysql_select_db($Database_Name, $DBConn) or die("Could not connect to database ($Database_Name). Perhaps you don't have the right permissions on this DB. Check your settings");

In the above code we use it for connecting to the database please give you database information like mysql username, password and host. We can import this into our action page.

Now we have created our config page to connecting our website to our MySQL its time to create an action page which actually performs action in storing the original url, throwing errors, creating a random alias name.

I hope you all got a clear picture in mentioned above. We exclusive covered the CSS and Front End part, now we need to create actions and validations page to shorten the link successfully.
For validating and showing results we will be using Mootools (a AJAX framework) i will not be explaining in detail on mootools right now.

Here is the actions.php file:

1.//To post values from index.html
2.$url=$_POST['originalurl'];
3.$alias=$_POST['alias'];
4.$count=0;

e are initially making count as 0 becomes this is being created for the first time.
Assigning orginalurl and alias to $url and $alias respectively.

Now we need to validate the URL as well as ALIAS.
Should Validate:
1. URL must be a URL and not just a TEXT
2. If alias field is blank then it must randomly create some characters.
3. If alias field has some value but its less than 3 characters then an error must be thrown.
4. Alias name shouldn’t contain any special characters.
4. If alias name is already being used by someone then again an error must be thrown.

So here is the code for that i will be using mootools so that i can display the result at the same page.

01.if(validate_url($url)==FALSE)
02.{
03.$result[] = 'Please enter only URL which start with http:// we wont allow you to tiny SHIT';
04.}
05.if($alias=='')
06.{
07.$alias=chr(rand(97,122)).chr(rand(97,122)).chr(rand(97,122));
08.}
09.if(strlen($alias)<3)
10.{
11.$result[] = 'Alias name must be greater than 3 chracters';
12.}
13.if(alpha_numeric($alias)==FALSE)
14.{
15.$result[] = 'No Special Characters must be used.';
16.}
17.if(alias_check($alias)==FALSE)
18.{
19.$result[] = 'Alias Name is already being used be someone, please specify another alias name';
20.}

In the above code we are using few functions (functin.php) like validate_url, alpha_numeric, alias_check and these functions are in function.php

01.unction alpha_numeric($alias)
02. {
03. return ( ! preg_match("/^([-a-z0-9])+$/i", $alias)) ? FALSE : TRUE;
04. }
05. function validate_url($url)
06. {
07. return (!preg_match("/http|ftp:\/\/(.*)\.(.*)/i", $url)) ? FALSE : TRUE;
08. }
09.function alias_check($alias)
10. {
11.include('config.php');
12.$sql="SELECT alias FROM url_tables WHERE alias='".$alias."'";
13.$result=mysql_query($sql);
14.$row=mysql_fetch_array($result);
15.if( mysql_num_rows($result) == 0 )
16.{
17. return(TRUE);
18.}
19.else{
20. return(FALSE);
21.}
22.
23. }

The $sql is used for checking the presence of alias name.

Now we completed the validation part. If everything goes well then we have to insert to our database.

Here is the code for that:

1.$query1 = mysql_query("INSERT INTO url_tables (alias,url,count) VALUES ('$alias','$url','$count')");

The mootools function that is being added on index.html is here:

1.<script src="mootools.js" type="text/javascript"><!--mce:0--></script>
2.<script type="text/javascript"><!--mce:1--></script>

Finally we completed 90% of our code. Its time for retrieving original URL from alias URL and also increment the count to show that the alias name was used.

We call this as original.php, in the page we grab the alias name check in out database and if found we pull the original URL else give an error showing that it is an invalid alias name.

01.$Not_Found = "reminder.html"; // The page to redirect to if no redirect link is found in the database.
02.$get_alias = $_SERVER['QUERY_STRING'];
03.$sql = mysql_query("SELECT url FROM url_tables WHERE alias='$get_alias'");
04. $site_arr = mysql_fetch_array($sql);
05. $site_redirect = $site_arr['url'];
06. if(!$site_arr){ header("Location: $Not_Found"); }
07. if($site_arr){
08. mysql_query("UPDATE url_tables SET ount = count + 1 WHERE alias='$get_alias'");
09. header("Location: $site_redirect");
10. }

$Not_Found is used to display a page if the alias name is invalid. And the remaining part is to query using Alias name as the ID and jump to the original URL. We also increment count = count + 1

Now making the magic of URL. Actually the above code works like this: http://gotiny.co.cc/original.php?example but we have to change it to http://gotiny.co.cc/example this is done by creating a .htaccess file
Here is the code:

RewriteEngine On
RewriteRule ^([a-zA-Z0-9_-]+)$ original.php?$1
RewriteRule ^([a-zA-Z0-9_-]+)/$ original.php?$1
ErrorDocument 404 /errror404.htm

At last we completed a bit.ly kind of site.


Popularity: 9% [?]

1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)
Loading ... Loading ...
Categories : PHP Tips, Webmaster Tips Tags : , , , ,


SEO Powered by Platinum SEO from Techblissonline