URI Shortener PHP Script

by Vincy. Last modified on February 11th, 2024.

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.

View Demo

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.

url shortener php script

Database script

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;

HTML view to input a long URL

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>

URL validation in jQuery

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;
}

PHP URL shortener script with Database insert

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.

  1. It generates a random 4-digit number to be used as a unique hash for the short URL. You can use an alternate strategy given below or plugin your custom rules here.
  2. Form the short URL by concatenating the application domain root with the random hash.
  3. Prepare query to insert URL mapping between the encoded original URL and generated 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.

Route the shortened URL to the original address

When running the short URL, it will redirect to the original URL. The following  PHP program fetches the redirect URL from the database.

  1. It forms the $shortURL by using the hash in the query string like $_GET["hash"].
  2. It gets the result from the database by the $shortURL.
  3. It redirects the user to the retrieved original URL using the header(“Location: …”) function.

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');
}

.htaccess to map the short URL to the application router

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

Leave a Reply

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

↑ Back to Top

Share this page