Last updated on July 31st, 2016 at 11:16 am

A URL shortener is very useful script to shorten your large url. In this post i explain you how to create a simple application for URL shortener. This is a very basic application and easy to understand and implement. I am using PHP and MySql to make this.

URL shorteners are being used more now than ever because people need to post short links on Twitter. Long links can sometimes take up the entire 140 character limit Twitter imposes on each ‘tweet’.  So, the solution is to shrink a long URL into a short one.

There are also no of website which provide you URL shortener service like Google URL Shortner.

 Example:

Orignal URL: http://trinitytuts.com/simple-url-shortener-script-using-php-mysql-2

Shorten URL: http://trinitytuts.com/MwZT

Code: URL Shortener script

Step 1. First we need to create a database and table in PHPMyAdmin where we can save original URL and Short url associated with it.

--
-- Database: `urlshortner`
--

-- --------------------------------------------------------

--
-- Table structure for table `urlshort`
--

CREATE TABLE IF NOT EXISTS `urlshort` (
  `id` int(100) NOT NULL AUTO_INCREMENT,
  `url` text NOT NULL,
  `short` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

Step 2. Now create new file i named as index.php. Here we first create connection to database and also make a form inside it note i write my whole code in a single page but you can create separate page and include it.

<?php
$con = mysql_connect("localhost", "root", "") or die("Connection error: ". mysql_error());
$db = mysql_select_db("urlshortner", $con);
?>

<form method="post" action="">
	<div>
		<label>URL</label>
		<input type="text" name="url" placeholder="Paste your URL">
	</div>
	<div>
		<input type="submit" value="Shorten">
	</div>
</form>

I also create a function through which we create a random string for our short url.

<?php
/*
	* Function to generate random string for unique url
*/
function randomUrl($type = 'alphanumeric', $length = 4){
	$str = '';
	switch($type):
		case 'alphanumeric':
			$possible = "23456789bcdfghjkmnpqrstvwxyzBCDFGHJKMNPQRSTVWXYZ";
		break;
		case 'alpha':
			$possible = "abcdefghijklmnopqrstuvwxyz";
		break;
		case 'numeric':
			$possible = "0123456789";
		break;
	endswitch;
	
	$i = 0;
	while ($i < $length) {
		$str .= substr( $possible, mt_rand( 0, strlen( $possible )-1 ), 1 );
		$i++;
	}
	return $str;
}
?>

After getting unique string for url we save it to database.

<?php
if(isset($_POST['url'])){
	// Get data 
	$url = mysql_real_escape_string($_POST['url']);
	$uniqueUrl = randomUrl($type = 'alphanumeric');
	$host = "http://localhost/UrlShortner/";
	// Insert data
	$ins = mysql_query("insert into `urlshort` set url='$url', short='$uniqueUrl'") or die(mysql_error());
	if($ins){
		echo "Your short url is created : <a href='".$host.$uniqueUrl."'>".$host.$uniqueUrl."</a>";
	}else{
		echo "Error: creating short url";
	}

}
?>

 Step 3.  Now after create a short url we need to make it work so we add .htaccess file in root directory/folder where we run this code. You need to enable your rewrite module to enable your url rewriting.

To enable rewrite module open: c:\xamp\apache\conf\httpd.conf and remove find

#LoadModule rewrite_module modules/mod_rewrite.so

Remove # from front of  it.

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.*)$ index.php?uri=$1 [L,QSA]

# secure htaccess file
<Files .htaccess>
 order allow,deny
 deny from all
</Files>

Step 4. Now when user click on your short link get the original link and redirect user to it.

if(isset($_REQUEST['uri'])){
	$req = mysql_real_escape_string($_REQUEST['uri']);
	$get = mysql_query("select * from urlshort where short='$req'");
	$url = mysql_fetch_array($get);
	if(mysql_num_rows($get) == 0){
		echo "Error invalid url";
		exit();
	}else{
		header('location: '.$url['url']);
		exit();
	}
	
}

Complete Code

<?php
$con = mysql_connect("localhost", "root", "") or die("Connection error: ". mysql_error());
$db = mysql_select_db("urlshortner", $con);

if(isset($_REQUEST['uri'])){
	$req = mysql_real_escape_string($_REQUEST['uri']);
	$get = mysql_query("select * from urlshort where short='$req'");
	$url = mysql_fetch_array($get);
	if(mysql_num_rows($get) == 0){
		echo "Error invalid url";
		exit();
	}else{
		header('location: '.$url['url']);
		exit();
	}
	
}
?>
<form method="post" action="">
	<div>
		<label>URL</label>
		<input type="text" name="url" placeholder="Paste your URL">
	</div>
	<div>
		<input type="submit" value="Shorten">
	</div>
</form>

<?php
if(isset($_POST['url'])){
	// Get data 
	$url = mysql_real_escape_string($_POST['url']);
	$uniqueUrl = randomUrl($type = 'alphanumeric');
	$host = "http://localhost/UrlShortner/";
	// Insert data
	$ins = mysql_query("insert into `urlshort` set url='$url', short='$uniqueUrl'") or die(mysql_error());
	if($ins){
		echo "Your short url is created : <a href='".$host.$uniqueUrl."'>".$host.$uniqueUrl."</a>";
	}else{
		echo "Error: creating short url";
	}

}
/*
	* Function to generate random string for unique url
*/
function randomUrl($type = 'alphanumeric', $length = 4){
	$str = '';
	switch($type):
		case 'alphanumeric':
			$possible = "23456789bcdfghjkmnpqrstvwxyzBCDFGHJKMNPQRSTVWXYZ";
		break;
		case 'alpha':
			$possible = "abcdefghijklmnopqrstuvwxyz";
		break;
		case 'numeric':
			$possible = "0123456789";
		break;
	endswitch;
	
	$i = 0;
	while ($i < $length) {
		$str .= substr( $possible, mt_rand( 0, strlen( $possible )-1 ), 1 );
		$i++;
	}
	return $str;
}
?>

 

Posted in: php