Saturday, August 4, 2012

Simple URL Shortener using PHP

There are a lot of major websites providing URL shortening services, to shorten URL to make them short and easy. In this tutorial we have successfully implemented a very simple to accomplish URL Shortener using PHP. So now, you can have your own URL shortener for your Website using this script.

In this script we have only used Php, for writing the Code. You must include the script in the Main folder of your Web project, to create direct shortened URLs like or you can save the script in any sub-folder inside main folder, but then shortened URL will be like


Index file holds the code for the form, to enter and submit the URL to be shortened. This form POST the URL to shortener.php , which displays the result.

<div id="container">
<form action="shortener.php" method="post">
Enter URL : <input type="text" name="url" id="textbox"/> </br>
<input type="submit" value="shorten" class="btn"/></br>


Here, the Posted URL value is collected, and a random String is generated for it. Using that randomly generated string as name, a new folder is created containing and index file with header value as the original URL.

<div id="container">
$pathname=base_convert($n,10,36); //random string generated
$file=$pathname . "/" . "index.php";
$fh= fopen($file,'w');
$string = "<?php header( 'Location:". $_POST["url"]."'); ?>";
echo "The shortened URL is: " . "<a href =" . $pathname . ">" . $pathname . "</a>";
//Replace with your domain name

Note : If you include the script into the main folder of your website then include your website's Domain name in the above code, in place of otherwise if you have included the script in any sub-folder then, replace with

  Newfolder - Index.php  

This Index file holds the code to redirect the page to the original URL.

<?php header( 'Location: Original URL'); ?>
//to redirect to the Original URL

1 comment: