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 http://www.wtfdiary.com/7as or you can save the script in any sub-folder inside main folder, but then shortened URL will be like http://www.wtfdiary.com/subfolder_name/7as

  Index.php  

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.

<body>
<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>
</form>
</div>
</body>


  Shortener.php  

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.

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

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 http://www.example.com otherwise if you have included the script in any sub-folder then, replace http://www.example.com with http://www.example.com/sub-folder

  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: