Url shortner in php

PHP |

1st Aug, 2019

Click here to share

Welcome again to another new tutorial on this great website.
Today we will be building an awesome URL shortener in PHP. To get started it is assumed that you already know about functions in PHP and a little bit of MySQL. If otherwise see our tutorials on those fields to get yourself up and running.
the following are the languages we will be using to build this application

  • PHP
  • MYSQL
  • HTML
  • CSS

In this tutorial, I will be using sublime text as the IDE and xampp as the local server. You are free to use anything you like but if you are yet to have a server running on your local machine see our tutorial on setting up a local server on windows.
Steps to building URL shortener in PHP.
Step one: create index.php
In the index.php file, we will create a form where a user has to input the URL he or she wants to shorten and after submission, the short URL will be returned. The short URL will now be used to access the long URL and you can even share the short URL to people for them to use and access the long URL.
Code example for index.php

 


<?php
include("config.php");
include("function.php");
$msg = "";
if(isset($_GET['r']) || !empty($_GET['r']))
{
$url_id = $_GET['r'];

// Checking database if the URL keyword is in it or not.
// If the query is true it will redirect to long URL.
// Otherwise it will redirect to index.php ( our home page )

$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');
}
}
if(isset($_POST["submit"]))
{
// Checking database if the Long URL already exists or not.
// If the result is true it will show a message that this URL already exit.
// Otherwise it will add to the database and you will get a short URL.

$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)
{
// URL Validation
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 = "<b>Your Short URL is</b>: <a href='".$short_url."'>$short_url</a>";
}
else
{
$msg = "There is some problem";
}
}
else
{
$msg = $_POST['long_url'] ."is not a valid URL";
}
}
else
{
$msg = "Sorry! This URL already exist.";
}
}
?>

 



<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>URL Shortener in PHP and MySQLi - Eggs Lab</title>
<style>
body
{
}

.inputBox
{
width:300px;
padding:10px;
font-size:17px;
font-family: sans-serif,Gill Sans, Gill Sans MT, Myriad Pro, DejaVu Sans Condensed, Helvetica, Arial;
}
.button
{
padding:10px;
color:#FFFFFF;
background-color:#9B0D9A;
border:0;
font-size:17px;
font-family:"Gill Sans", "Gill Sans MT", "Myriad Pro", "DejaVu Sans Condensed", Helvetica, Arial, sans-serif;
}
.msg
{
font-size:17px;
font-family:"Gill Sans", "Gill Sans MT", "Myriad Pro", "DejaVu Sans Condensed", Helvetica, Arial, sans-serif;
}
.outer {
display: table;
position: absolute;
height: 50%;
width: 99%;
text-align:center;
}

.middle {
display: table-cell;
vertical-align: middle;
}

</style>
</head>

<body>
<div style="margin:0 auto; width:500px; text-align:center; font-family:Gotham, 'Helvetica Neue', Helvetica, Arial, sans-serif;">
<h1>How to Make Basic URL Shortener in PHP and MySQLi</h1>
<p><a href="http://www.worldtok.com/">Back to tutorial</a></p>
</div>
<div class="outer">
<div class="middle">
<form method="post">
<input type="url" name="long_url" class="inputBox" required>
<input type="submit" name="submit" class="button" value="Short it!" >
</form>
<h2 class="msg"><?php echo $msg;?></h2>
</div>
</div>
</body>
</html>

 


That is the basic index page.
Create another file called function.php
In this file, we will write some logic. This logic will be to generate a random unique string at every request. That is every time a user requests to shorten a given URL. This random string, however, must be unique for every URL stored in the database because it is the unique identifier used for accessing each URL.
In the function write the following code


<?php
function generateRandomString()
{
$characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
$charactersLength = strlen($characters);
$randomString = '';

for ($i = 0; $i < 5; $i++)
{
$randomString .= $characters[rand(0, $charactersLength - 1)];
}

return $randomString;
}

?>

 


Now that we have written the function download the complete project here and extract the file into your project directory.
Head over to your phpMyAdmin and create a database called Worldtok.
Open config.php(part of the file you download) in your suitable ide and add you're necessary database connection options otherwise this won't work.
Run the db.php file on your browser. This will create table url_shortner inside your database specifies in config.php with the following columns

(url_id, log_url and short_url).


Open index.php in your browser and finally, everything will now work fine. Play with the code and practice it if you encounter any problem come back to this tutorial and you will be able to solve it.
Download the code for the whole tutorial here
Hope you enjoyed the tutorial, don’t forget to subscribe so that you won’t miss any of the upcoming tutorials

Leave a Reply

RELATED POSTS


Total of 0 Comment