Create Your Own URL Shortening Service Using PHP & jQuery


I made a URL shortening service a year back using PHP & jQuery. It was pretty simple. You should know the concept of URL Shortening. The concept is simple. When a user sends a request to short a URL, PHP will check if the URL is valid. If it’s valid then PHP will make a string of 5 or 6 characters. A folder is created with the name of this string and an index.php file with header function code is created in this folder. This will make the folder redirect to the URL the user requested. Since it’s a folder no extensions will be seen ! So You can make up some pretty good URL‘s.

Here is the form for URL Shortening :


 

   

   

   Type in a URL and click on Short URL ! to start shorting.
 

 

   

 

 

   

Shorting Successful


   Here is Your Shorted URL :
 

 

   

Invalid URL


 

 

 

We also added a loader div, success div and an error div in the

 tag. The jQuery code plays a vital role in this process because we are not adding any action attributes in the form, so if jQuery fail to load then the conversion won’t work. Here is the jQuery code :

Insert the above code anywhere you like. The jQuery will check if the URL is valid and will send a POST request to add.php when user submits the form. If the URL is not valid, then jQuery will show the error div. Here is the add.php file :

<?
header(‘Content-Type: text/html’);
function rantext($length){$chars=”abcdefghijklmnopqrstuvwxyzsubinsblogABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789″;$size=strlen($chars);for($i=0;$i<$length;$i++){$str.=$chars[rand(0,$size-1)];}return $str;}
$dir=”/urls/”;/*Directory to store URL’s. If main folder use “/” */
$url=$_POST[‘url’];
if(!preg_match(“/^(http://|https://|ftp://){1}([0-9A-Za-z]+.)/”,$url)){
 die(‘{“stat”:”0″}’);
}
$name = rantext(5);
if (file_exists($name)){
 $name = rantext(6);
}else{
 mkdir(‘.’.$dir.$name);
 $subinsbshort = fopen(‘.’.$dir.$name.’/index.php’, ‘x’) or die(‘{“stat”:”0″}’);
}
if(fwrite($subinsbshort,’<?header(“Location:’.$url.’”);?>’)){
 echo ‘{“stat”:”1″,”url”:”//demos.subinsb.com/url-shortener’.$dir.$name.’”,”name”:”‘.$name.’”}’;
}else{
 die(‘{“stat”:”0″}’);
}
fclose($subinsbshort);
?>

We also added the Random String Function to the add.php available from here. The Function will generate a string of 5 characters. If the string created is already used, then the script will generate another string of 6 characters. Then the add.php will create a folder with the name of random string. The add.php returns a JSON data to jQuery. jQuery will process the data and if everything is OK, then jQuery will show a success message with the new shorted URL.
If you have any suggestions/problems/feedback say it out in the comments, I will help you.
And Happy Birthday Google.