You might be using bit.ly, goo.gl, tinyurl.com or maybe some other URL shortener service to shorten your URL. It’s true that long URL doesn’t look pretty when you are sharing it with your friends or colleagues through email or messages. And I agree for every problem there is a solution on the internet.
When you have already too many sites available on the internet to shorten your URL, then why you need your own? Why you have finasteride online? This is because you want to use your own company domain to make URL Shorten. Why depend on others when you have an option?
Obviously, you will prefer your own one. In this tutorial, I am going to show that “How to Make a Basic URL Shortener in PHP and MySQLi”.
[button-blue url=”http://demos.eggslab.net/basic-url-shortener-php-mysqli/” target=”_self” position=””]Live Demo[/button-blue][button-green url=”http://demos.eggslab.net/downloads/11″ target=”_self” position=””]Download[/button-green]
How does a URL Shortener Work?
The concept behind a URL Shortener is very easy and understandable. Basically, when you enter your long URL in URL Shortener Web App it generate a random string and store it in the database along with your long URL and short URL as well. So whenever someone try to open that short URL, it will search in the database if the provided short URL exist in the database or not. If it exists in database then it will retrieve the long URL and redirect you to that long URL. Wait a minute, does I told you that how it generate short URL? No? Remember I told you that it generate a random string, that string plus your domain is your short URL. It acts like a unique keyword for your long URL. Suppose, your domain is mydomain.com and the generated string is “xRb3p” then your short URL will look like mydomain.com/xRb3p.
Let’s see how to make such magical app.
1. Database
The first and the foremost thing is a the database. Here is database structure for our small app.
CREATE TABLE `url_shortner` ( `url_id` varchar(5) NOT NULL, `long_url` varchar(255) NOT NULL, `short_url` varchar(50) NOT NULL, PRIMARY KEY (`url_id`) );
2. config.php
This file contains basic MySQL database connection detail.
define('DB_SERVER', 'localhost'); define('DB_USERNAME', 'root'); define('DB_PASSWORD', ''); define('DB_DATABASE', 'eggslab'); $db = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE); $site = "http://localhost/eggslab/url-shortner";
The variable “$site” contain your website URL for which you are going to make URL Shortener. In my case, this is localhost URL. You should have to change all values of this file. So your app can connect to your desired database correctly.
3. functions.php
This file contains the function. It has only one function that we are going to use to generate a random string.
function generateRandomString() { $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < 5; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; }
4. index.PHP
First of all, we will build a basic HTML form to let the user input URL and submit it for further processing.
<form method="post"> <input type="text" name="long_url" > <br> <input type="submit" name="submit" value="Short it!" > </form>
Now have a look at PHP code. Now we have to execute PHP code when user hit ‘Submit’ button.
if(isset($_POST["submit"])) { // Code to be executed. }
Under this ‘if statement’ we will first execute a simple query to check whether the link user input has already exist or not.
$long_url = $_POST["long_url"]; $long_url = mysqli_real_escape_string($db, $long_url); $sql="SELECT long_url FROM url_shortner WHERE long_url = '$long_url'"; $result=mysqli_query($db,$sql); $row=mysqli_fetch_array($result,MYSQLI_ASSOC); if(mysqli_num_rows($result) == 0) { }
Now if this statement will become true we will check that user input URL is valid URL or not. If it is valid we will execute INSERT query otherwise show error.
if (!filter_var($_POST['long_url'], FILTER_VALIDATE_URL) === false) { $url_id = generateRandomString(); $short_url = $site . "/" . $url_id; $query = mysqli_query($db, "INSERT url_shortner (url_id, long_url, short_url) VALUES ('$url_id','$long_url','$short_url')"); if($query) { $msg = $short_url; } else { $msg = "there is some problem"; } } else { $msg = $_POST['long_url'] ."is not a valid URL"; }
This was just a basic section for inserting new link or checking if link already exist or not. Fine, let’s take a look on how user will redirect to real page I mean long URL. So here is the code.
if(isset($_GET['r']) || !empty($_GET['r'])) { $url_id = $_GET['r']; $sql = "SELECT long_url FROM url_shortner WHERE url_id = '$url_id'"; $result = mysqli_query($db,$sql); $row = mysqli_fetch_array($result,MYSQLI_ASSOC); if(mysqli_num_rows($result) == 1) { $l_url = $row['long_url']; header('Location:' .$l_url); } else { header('Location: index.php'); } }
Here what I have done is that I have check if user comes with any keyword (refer to short link unique key) then we will fetch the required data from database if there is any, otherwise redirect to our homepage. How the user come with any keyword?
http://localhost/eggslab/url-shortner/?r=vkTT0
This is a simple example. Isn’t look bad? Why not to make it pretty to attract the user.
We are going to rewrite URL. To make http://localhost/eggslab/url-shortner/?r=vkTT0 to http://localhost/eggslab/url-shortner/vkTT0 we are going to make .htaccess file and write the following code.
RewriteEngine On RewriteRule ^([a-zA-Z0-9_-]+)$ index.php?r=$1 RewriteRule ^([a-zA-Z0-9_-]+)/$ index.php?r=$1
Final Words
So it was just a basic URL Shortener App. If you want to new features in it, it totally depends on you. For example you want to add authentication feature in it, you can do it I have already written a full detail article on (PHP Login System). Even if you want all generated short links in a single page you can simply apply SELECT query and display all links right in one place. Well, it’s all depends on you. If you want any type of help from me you can comment below, message us on facebook. And yes you can write me an email too at abdullah@eggslab.net. If you have any problem, any suggestion or any feedback you are warmly welcome to comment below. And don’t forget to subscribe our blog to get every new article direct in your inbox 😉
[button-blue url=”http://demos.eggslab.net/basic-url-shortener-php-mysqli/” target=”_self” position=””]Live Demo[/button-blue][button-green url=”http://demos.eggslab.net/downloads/11″ target=”_self” position=””]Download[/button-green]
Leave a Reply