Programing Archive

How to start your own tinyurl (For Dummies)

url-short-service

Ever wanted to start your own tiny url website ? This post is for the people who wanted to start there own tiny url or shorten url service with minimum technical knowledge.

In this example we have taken a example of http://tinurl.co

What is required ?

You need a domain name (really short) and a linux shared hosting service a basic knowledge of PHP, Mysql and Apache.

The web site structure
For creating a tiny url like website you need five files in total :

1: Index.php :

This is your main page, which ask user for the main url or long url to shorten the same.

2: random.php :

This file will create a shorten url for the entered long url.

3: redirect.php :

This is a standalone file which will actually do the redirection to long url when user refer the shorten url.

4: .htaccess

.htaccess file tell the apche server how to treat some special request like 404 error or any redirection and much more. In this case it will tell the apache server about the redirection method to use for shorten url.

5:  db.php

Over here we will store the database connection for mysql.

The Mysql Structure :

This is very simple database structure i ever used. There is only one table here which i named as  ” link ” because it will store all the requested long url and there shorter form.

The Table structure will have three fields :

1: sno

A auto increment field int value, this will your primary key.

2. actualurl

This field with VARCHAR type and limit of 255 will store the actual long url entered by the user.

3. tiny

As the name implement it will store the shorten form of entered long url.

Ok, now lots of theory is done here lets work on the coding part, I will go page wise :

db.php

<?php
 
$my_host = 'localhost'; // your host here
 
$my_user = 'db_username'; // your database url
 
$my_pass = 'db_password'; // your database password
 
$my_database = 'db_name'; // your database name
 
// database connection string
$conn = mysql_connect($my_host, $my_user, $my_pass) or die  ('Error connecting to mysql');
 
@mysql_select_db("my_$database") or die( "Unable to select database");
 
?>

index.php

<?php
include_once('db.php'); // making the db connection
 
?>
<!--  java script to verify the user input like it should be with http:// -->
<SCRIPT LANGUAGE="JavaScript"> 
 
function Validate(form) {
    var v = new RegExp();
    v.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$");
    if (!v.test(form["textfield"].value)) {
        alert("You must supply a valid URL.");
        return false;
    }
} 
 
</SCRIPT> 
 
<body topmargin="0" leftmargin="0">
<table width="100%" border="0">
  <tr>
    <td height="64" colspan="2" bgcolor="#003333"><h1 class="style2">URL shortener tools</h1></td>
  </tr>
  <tr>
    <td width="7%">&nbsp;</td>
    <td width="93%">
 <?php
 if($_POST[textfield] != '')
 {
 
 include_once('random.php');
 $query = "select * from links where actualurl ='$_POST[textfield]' limit 1";
 $result = mysql_query($query) or die(mysql_query());
$count1 = mysql_num_rows($result);
 if($count1 =='0')
 {
  mysql_query("insert into links (actualurl,tiny) values ('$_POST[textfield]','$pwd')") or die(mysql_error());
 
  }else
  {
  	while($row = mysql_fetch_array($result))
	{
 
	$pwd = $row[tiny];
	}
 
  }
  ?>
    <table width="60%" border="1" align="center">
  <tr>
    <td>
        http://tinurl.co/<?php echo $pwd; ?> <a href="http://tinurl.co/<?php echo $pwd; ?>" target="_blank"><img src="images/bullet1.gif" width="8" height="9" border="0" /> </a>      </td>
  </tr>
</table>
    <br />
    <?php
}
?>
 
    <form id="form1" name="form1" method="post" action="" onSubmit="return Validate(this);">
      <table width="75%" border="0" align="center">
        <tr bgcolor="#CCCCCC">
          <td colspan="2"><span class="style1">Enter Your URL Bellow :</span></td>
          </tr>
        <tr>
          <td width="24%">Your Big URL with http://</td>
          <td width="76%"><label>
            <input name="textfield" type="text" id="textfield"  size="50" />
            <input type="submit" name="button" id="button" value="Submit" />
          </label></td>
        </tr>
        <tr>
          <td colspan="2"> Custom Link   http://tinurl.co/
            <label>
            <input type="text" name="c" id="c" />
            (Optional)</label></td>
          </tr>
        <tr>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
        </tr>
      </table>
      </form>
    </td>
  </tr>
</table>
</body>

3: random.php

<?php
$min=3; // minimum length of url
$max=4; // maximum length of url
$pwd=""; // to store generated url
 
for($i=0;$i<rand($min,$max);$i++)
{
 
	// to see if the entered url is already present in db
	$query = "select * from links where tiny ='$pwd'";
	$result = mysql_query($query) or die(mysql_error());
	$count_db = mysql_num_rows($result);
	if($count_db =='0')
	{
		$num=rand(48,122);
 
	  if(($num > 97 && $num < 122))
	  {
		  $pwd.=chr($num);
	  }
 
	  else if(($num > 65 && $num < 90))
	  {
		  $pwd.=chr($num);
	  }
 
	  else if(($num >48 && $num < 57))
	  {
		  $pwd.=chr($num);
	  }
 
	  else if($num==95)
	  {
		  $pwd.=chr($num);
	  }
 
	  else
	  {
		  $i--;
	  }
  }
}
 
//echo $pwd; // prints the password
 
?>

4. redirect.php

<?php
  require("./db.php");
 
  $short = $_REQUEST['short'];
 
    $query = mysql_query("SELECT * FROM links WHERE `tiny`='".mysql_escape_string($short)."' LIMIT 1");
    $row = mysql_fetch_row($query);
 
    if(!empty($row)) {
      Header("HTTP/1.1 301 Moved Permanently");
      header("Location: ".$row[1]."");
    } else {
      $html = "Error: cannot find short URL";
    }
 
  mysql_close($db);
?>

5: .htaccess

RewriteEngine on
 
RewriteCond %{HTTP_HOST} ^www.tinurl.co$
RewriteRule ^/?$ "http\:\/\/tinurl\.co" [R=301,L]
RewriteRule ^(\w+)$ ./redirect.php?short=$1

I hope that you enjoyed reading this post and you will be now able to start your own tiny url website. Enjoy ….

To get your domain name registered and linux hosting your can visit NetSpaceIndia.com

PHP Upload with Ajax

ajax_upload

Recently i wanted to create a simple php based upload with reloading the page. This script dose the same job :

You need to remember to  make your upload folder as writable and one more thing, ajax do not support upload function thats the reason we are using php for uploading but this script does give you a feel of ajax.

You need only need to include two file one java script “ajaxupload.js” and one php script “ajaxupload.php”.

Step 1:
include your java script

<script src="scripts/ajaxupload.js" type="text/javascript"></script>

Step2 :

With the upload you can specify the following type :

<!–

VERY IMPORTANT! Update the form elements below ajaxUpload fields:
1. form – the form to submit or the ID of a form (ex. this.form or standard_use)
2. url_action – url to submit the form. like ‘action’ parameter of forms.
3. id_element – element that will receive return of upload.
4. html_show_loading – Text (or image) that will be show while loading
5. html_error_http – Text (or image) that will be show if HTTP error.
VARIABLE PASSED BY THE FORM:
maximum allowed file size in bytes:
maxSize = 9999999999
maximum image width in pixels:
maxW = 200
maximum image height in pixels:
maxH = 300
the full path to the image upload folder:
fullPath = http://blog.netspaceindia.com/demo/php_ajax_image_upload/uploads/
the relative path from scripts/ajaxupload.php -> uploads/ folder
relPath = ../uploads/
The next 3 are for cunstom matte color of transparent images (gif,png), use RGB value
colorR = 255
colorG = 255
colorB = 255
The form name of the file upload script
filename = filename
–>

In your main html file place form tag like :

<form action="scripts/ajaxupload.php" method="post" name="standard_use" id="standard_use" enctype="multipart/form-data">
 
<p><input type="file" name="filename" /></p>
 
 <button onclick="ajaxUpload(this.form,'scripts/ajaxupload.php?filename=filename&amp;maxSize=9999999999&amp;maxW=200&amp;fullPath=http://blog.netspaceindia.com/demo/php_ajax_image_upload/uploads/&amp;relPath=../uploads/&amp;colorR=255&amp;colorG=255&amp;colorB=255&amp;maxH=300','upload_area','File Uploading Please Wait...&lt;br /&gt;&lt;img src=\'images/loader_light_blue.gif\' width=\'128\' height=\'15\' border=\'0\' /&gt;','&lt;img src=\'images/error.gif\' width=\'16\' height=\'16\' border=\'0\' /&gt; Error in Upload, check settings and path info in source code.'); return false;">Upload Image</button>
</form>

Create a folder with name upload and enjoy.

Read the rest of this entry »