How to Create URL Shortener Tool With PHP

This article is about how to create shorten URL using PHP. First of all, we must know what is shorten URL.

URL shortening is a process to make lengthy URLs too short. Shortened URL is mainly useful for sharing on social media in such cases when there is word limitation.

Shorten URL is also easy to add on website or blog for the link. We get the advantage of shorten URL when need to share the link on Twitter due to limitations of character.

Lengthy URL is changed to short by using random string for each using some inbuilt function of PHP. As we can see in given example.

For e.g:
http://www.phpcluster.com/multi-step-form-using-javascript-css.html
is changed to
http://urlshortner.phpcluster.com/wz0nr2

How to Create URL Shortener Tool With PHP

as you can see in the given below pic to get a better

Now when a user clicks on shortened URL then by getting query string from it retrieve the main link and will get redirected to the original lengthy structure URL.

File Structure

There are two files used to create a URL shortener tool with PHP which is as follows:
index.php – contains a form to provide a lengthy URL and function to create a short string for it and store it in the database. Also, contain a script to redirect from shorten URL to the main link.
.htaccess – when a user clicks on shortened URL then get query string from it and send it to index.php.


index.php

<?php 
//config
mysql_connect('localhost','user','password');
mysql_select_db('dbname');

//get main url to redirect
if(!empty($_GET['url']))
{
$real_link = mysql_fetch_array(mysql_query("SELECT `links` FROM `urls` WHERE `short_url` = '".addslashes($_GET['url'])."'"));
$redirect_url = $real_link['links'];
header("HTTP/1.1 301 Moved Permanently");
header("Location: ".$redirect_url);
}
if(isset($_POST['url']))
{
//random string for url 
$string1 = "abcdefghijklmnopqrstuvwxyz1234567890";
$string = str_shuffle($string1);
$shorten_url = substr($string,0,6);
mysql_query("INSERT INTO `urls`(`links`,`short_url`) VALUES('".addslashes($_POST['url'])."','".addslashes($shorten_url)."')");
}
?>
<form method="POST">
<input type="text" name="url">
<input type="submit" name="submit" value="Shorten URL">
</form>

.htaccess

RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)  index.php?url=$1 [L,QSA]

DB Structure

There are three column we used here which are as follows

How to Create URL Shortener Tool With PHP

Id – this is used as auto increment id
Links – this one is used to store lengthy long url
Short_url – is used to store short string generated for lengthy URL

If you liked this article 🙂 please share with your friends and colleagues 🙂 .Click on the download button to get a complete zip file.

If you have any query feel free to write in the comment box.

1 thought on “How to Create URL Shortener Tool With PHP”

Leave a Comment