The URL shortener tool is to covert a lengthy URL into a short one. There are many online tools to get a short URL by entering a long URL.
The short URL output uses a hash or short code that creates a unique URL to map the original one. It is like creating a pretty URL routed through the application handle via .htaccess rules.
The mapping persists on the application storage resource, mostly the database.
This example has code to learn how to create a URL shortener online tool in PHP.
The URL shortener returns a short link that can be kept in mind to share and promote spontaneously. Dealing with short URLs has many advantages and mainly it brings more direct hits to the pages.
This SQL script contains an INSERT statement to have the URL mapping table with a proper key index. It contains the data to retrieve the target URLÂ mapped to the short link.
DataSource.php
--
-- Database: `php-short-url`
--
-- --------------------------------------------------------
--
-- Table structure for table `tbl_url`
--
CREATE TABLE `tbl_url` (
`id` int(30) NOT NULL,
`short_url_hash` varchar(255) NOT NULL,
`original_url` varchar(255) NOT NULL
);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tbl_url`
--
ALTER TABLE `tbl_url`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `tbl_url`
--
ALTER TABLE `tbl_url`
MODIFY `id` int(30) NOT NULL AUTO_INCREMENT;
This HTML code has the form to collect a URL from the user. The user-entered value is sent to the URL shortening script in PHP. Then, the view displays the short URL generated in PHP.
The below code contains a jQuery form validation function. It validates and confirms that the URL field is not empty and the data matches with the given regex pattern. In a previous tutorial, we used a regex password validation script in PHP.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<meta name="description" content="" />
<meta name="author" content="" />
<title>URL Shortener PHP Script</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link href="./assets/css/form.css" rel="stylesheet" />
<link href="./assets/css/style.css" rel="stylesheet" />
</head>
<body>
<div class="phppot-container">
<h1>URL Shortener PHP Script</h1>
<div class="phppot-message"></div>
<form id="frm-url-shortener" method="post" onSubmit="return validateLongURL()">
<div class="row">
<label>Enter long URL</label>
<input class="full-width" type="text" name="original_url" id="original_url"
placeholder="e.g. http://www.example.com/querystring" autocomplete="off" />
</div>
<div class="row">
<input name="btn_submit" type="submit" value="Create Short URL" />
</div>
</form>
<?php
if (!empty($originalURL) && !empty($shortURL)) {
?>
<div class="shortened-url-response">
<p>
<label>Orginal URL:</label>
<span id="original_url_response">
<?php if ($originalURL) {
echo urldecode($originalURL);
} ?>
</span>
</p>
<p>
<label>Short URL:</label>
<?php require_once __DIR__ . "/Config.php"; ?>
<span id="shortened_url_response">
<?php if ($shortURL) {
echo Config::ROOT_URL . $shortURL;
} ?>
</span>
</p>
</div>
<?php } ?>
</div>
</body>
</html>
The below function is part of the URL shortening tool landing page. It checks if the entered long URL is in the regex pattern defined. Pattern matching is a way to do format validations with regex on the email, password, or URL entered by the user.
function validateLongURL() {
var valid = true;
var message = "";
$('.phppot-message').removeClass('error').html('').hide();
var originalURL = $('#original_url').val();
var urlRegexPattern = /^(ftp|http|https):\/\/[^ "]+$/;
if (originalURL === "") {
message = 'URL is required.';
valid = false;
} else if (!urlRegexPattern.test(originalURL)) {
message = 'Invalid URL';
valid = false;
}
if(!valid) {
$('.phppot-message').addClass('error').html(message).show();
}
return valid;
}
On submission, the URL shortener tool posted the long URL entered by the user to the PHP. It finds the post data in $_POST["original_url"]
and encodes it using PHP urlencode()
.
It performs the following functions to generate a short URL.
<?php
if (isset($_POST["btn_submit"])) {
require_once __DIR__ . "/DataSource.php";
if (!empty($_POST["original_url"])) {
$originalURL = urlencode($_POST["original_url"]);
$shortURL = mt_rand(1000, 9999);
$query = "INSERT INTO tbl_url (short_url_hash, original_url) VALUES (?, ?)";
$paramType = "ss";
$paramValueArray = array($shortURL, $originalURL);
$ds = new DataSource();
$ds->insert($query, $paramType, $paramValueArray);
}
}
?>
// Function to generate a random string of specified length
function generateRandomString($length = 6) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
return $randomString;
}
The above function generates a random string of the given length. When you have a large number of URLs to convert mt_rand can give repetitive results. The uniqueness is not guaranteed. I have used mt_rand to present you with an overall structure and a simplified use case for your understanding and implementation. You have the freedom to choose between mt_rand or the above generateRandomString function or your custom strategy depending on your use case.
When running the short URL, it will redirect to the original URL. The following PHP program fetches the redirect URL from the database.
$_GET["hash"]
.router.php
<?php
require_once __DIR__ . "/DataSource.php";
$query = "SELECT * FROM tbl_url WHERE short_url_hash = ?";
$paramType = "s";
$paramValueArray = array($_GET["hash"]);
$ds = new DataSource();
$result = $ds->select($query, $paramType, $paramValueArray);
if(!empty($result[0]["original_url"])) {
header("Location: " . urldecode($result[0]["original_url"]));
} else {
header('HTTP/1.0 404 Not Found');
}
The following rules allow redirecting to an original URL when entering a short URL on the browser.
.htaccess
RewriteEngine on
RewriteBase /url_short/
RewriteRule ^([0-9]+)$ router.php?hash=$1 [L,QSA]
Make sure that your server is mod-rewrite enabled to let the .htaccess work.
If not, you can apply PHP explode the current URL by “/”. Then, it returns an array to find the short URL hash to fetch the target URL from the database.
View Demo Download