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 URL to short. Shortened URL is mainly useful for sharing on social media in such case when there is word limitation.

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

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

For e.g:
is changed to

as you can see in given below pic to get better
How to Create URL Shortener Tool With PHP
Now when a user click on shortened URL then by getting query string from it retrieve main link and will get redirected to original lengthy structure URL.

File Structure

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


//get main url to redirect
$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);
//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">


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 download button to get complete zip file. If you have any query feel free to write in comment box.

One thought on “How to Create URL Shortener Tool With PHP

Leave a Reply

Your email address will not be published. Required fields are marked *