AllsWeb Blog
No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
Support
Knowledgebase
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison
No Result
View All Result
AllsWeb White Logo
No Result
View All Result
Home PHP and MySQL

Create Short URL using PHP URL Shortener

Create Short URL using PHP URL Shortener

Lakshika Mathur by Lakshika Mathur
December 29, 2019
Reading Time: 7 mins read
0
Create Short URL using PHP URL Shortener

A short URL always a suggested way to share the web page URL. It is a simple way to remember. Also, you can share it easily on the web. There are multiple URL Shortener services available that offer you to convert long URLs to short URL online. But the main drawbacks of these services are you won’t be able to use your domain in the short URL. Therefore, if you want to make a short URL with your domain name, you need to use a custom URL Shortener.

RELATED POSTS

What is Application Programming Interface (APIs)?

Like Dislike Rating System with jQuery, Ajax, and PHP

Star Rating System with jQuery, Ajax, PHP, and MySQL

The URL shortener service takes a long URL and compresses it into a short link, which is easy to share. You can generate a short URL programmatically with the help of PHP without any third party URL Shortener API. In this tutorial, we will explain to you how to build a URL Shortener library and create a short URL using PHP and MySQL. Therefore, with the PHP URL Shortener library, you can shorten the long URLs and use your domain in the short URLs.

Our sample script shows the process of creating a clean and short link that can be shared easily via email or social media. Therefore, you can use the database to store the info about long and short URL. Also, you can trace the number of views the short URL gets by the visitors.

Make Database Table

Use the database to handle the redirection grounded on the shortcode. The following SQL makes a short_urls table in the MySQL database to store URL info (long URL, shortcode, hits, and build time).

URL Shortener Library (Shortener.class.php)

CREATE TABLE `short_urls` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `long_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `short_code` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `hits` int(11) NOT NULL,
 `created` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

The URL Shortener class allows creating a short URL using PHP and MySQL programmatically. It uses PDO Extension to work with the MySQL database. Therefore, the PDO object instance is required on the initialization of the Shortener class.

Static Variables:

  • $chars – Allowed characters for the short code. (Characters group is separated by |)
  • $table – Database table name to store the URL and quick code info.
  • $checkUrlExists – Set to TRUE. 
  • $codeLength – The length of the short code characters.

Functions:

  • __construct() – Set PDO object reference and timestamp.
  • urlToShortCode() – Validate URL and create short code.
  • validateUrlFormat() – Validate the format of the URL.
  • verifyUrlExists() – Verify the URL, whether it exists or not using cURL in PHP.
  • urlExistsInDB() – Check whether the long URL exists in the database. If exist, return the shot code, otherwise, return FALSE.
  • createShortCode() – Create a short code for the long URL and insert the long URL & short code in the database.
  • generateRandomString() – Generate random string (short code) with the specified characters in the $chars variable.
  • insertUrlInDB() – Insert URL info in the database using PDO Extension and MySQL and return the row ID.
  • shortCodeToUrl() – Convert the short code to long URL and insert the hits count in the database.
  • validateShortCode() – Validate the short code based on the allowed characters.
  • getUrlFromDB() – Fetch the long URL from the database based on the short code.
  • incrementCounter() – Increment the URL visits counter in the database for a particular record.
<?php
/** 
 * Class to create short URLs and decode shortened URLs
 * 
 * @author Allsweb.com <[email protected]> 
 * @copyright Copyright (c) 2018, Allsweb.com
 * @url https://www.allsweb.com
 */ 
class Shortener
{
    protected static $chars = "abcdfghjkmnpqrstvwxyz|ABCDFGHJKLMNPQRSTVWXYZ|0123456789";
    protected static $table = "short_urls";
    protected static $checkUrlExists = false;
    protected static $codeLength = 7;

    protected $pdo;
    protected $timestamp;

    public function __construct(PDO $pdo){
        $this->pdo = $pdo;
        $this->timestamp = date("Y-m-d H:i:s");
    }

    public function urlToShortCode($url){
        if(empty($url)){
            throw new Exception("No URL was supplied.");
        }

        if($this->validateUrlFormat($url) == false){
            throw new Exception("URL does not have a valid format.");
        }

        if(self::$checkUrlExists){
            if (!$this->verifyUrlExists($url)){
                throw new Exception("URL does not appear to exist.");
            }
        }

        $shortCode = $this->urlExistsInDB($url);
        if($shortCode == false){
            $shortCode = $this->createShortCode($url);
        }

        return $shortCode;
    }

    protected function validateUrlFormat($url){
        return filter_var($url, FILTER_VALIDATE_URL, FILTER_FLAG_HOST_REQUIRED);
    }

    protected function verifyUrlExists($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_NOBODY, true);
        curl_setopt($ch,  CURLOPT_RETURNTRANSFER, true);
        curl_exec($ch);
        $response = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        return (!empty($response) && $response != 404);
    }

    protected function urlExistsInDB($url){
        $query = "SELECT short_code FROM ".self::$table." WHERE long_url = :long_url LIMIT 1";
        $stmt = $this->pdo->prepare($query);
        $params = array(
            "long_url" => $url
        );
        $stmt->execute($params);

        $result = $stmt->fetch();
        return (empty($result)) ? false : $result["short_code"];
    }

    protected function createShortCode($url){
        $shortCode = $this->generateRandomString(self::$codeLength);
        $id = $this->insertUrlInDB($url, $shortCode);
        return $shortCode;
    }
    
    protected function generateRandomString($length = 6){
        $sets = explode('|', self::$chars);
        $all = '';
        $randString = '';
        foreach($sets as $set){
            $randString .= $set[array_rand(str_split($set))];
            $all .= $set;
        }
        $all = str_split($all);
        for($i = 0; $i < $length - count($sets); $i++){
            $randString .= $all[array_rand($all)];
        }
        $randString = str_shuffle($randString);
        return $randString;
    }

    protected function insertUrlInDB($url, $code){
        $query = "INSERT INTO ".self::$table." (long_url, short_code, created) VALUES (:long_url, :short_code, :timestamp)";
        $stmnt = $this->pdo->prepare($query);
        $params = array(
            "long_url" => $url,
            "short_code" => $code,
            "timestamp" => $this->timestamp
        );
        $stmnt->execute($params);

        return $this->pdo->lastInsertId();
    }
    
    public function shortCodeToUrl($code, $increment = true){
        if(empty($code)) {
            throw new Exception("No short code was supplied.");
        }

        if($this->validateShortCode($code) == false){
            throw new Exception("Short code does not have a valid format.");
        }

        $urlRow = $this->getUrlFromDB($code);
        if(empty($urlRow)){
            throw new Exception("Short code does not appear to exist.");
        }

        if($increment == true){
            $this->incrementCounter($urlRow["id"]);
        }

        return $urlRow["long_url"];
    }

    protected function validateShortCode($code){
        $rawChars = str_replace('|', '', self::$chars);
        return preg_match("|[".$rawChars."]+|", $code);
    }

    protected function getUrlFromDB($code){
        $query = "SELECT id, long_url FROM ".self::$table." WHERE short_code = :short_code LIMIT 1";
        $stmt = $this->pdo->prepare($query);
        $params=array(
            "short_code" => $code
        );
        $stmt->execute($params);

        $result = $stmt->fetch();
        return (empty($result)) ? false : $result;
    }

    protected function incrementCounter($id){
        $query = "UPDATE ".self::$table." SET hits = hits + 1 WHERE id = :id";
        $stmt = $this->pdo->prepare($query);
        $params = array(
            "id" => $id
        );
        $stmt->execute($params);
    }
}

SEE ALSO: Highlight Keyword in Search Results with PHP and MySQL

Database Configuration (dbConfig.php)

You can use dbConfig.php to connect and select the database. Specify the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName) as per your MySQL database server credentials.

<?php
// Database configuration
$dbHost     = "localhost";
$dbUsername = "root";
$dbPassword = "root";
$dbName     = "allsweb";

// Create database connection
try{
    $db = new PDO("mysql:host=$dbHost;dbname=$dbName", $dbUsername, $dbPassword);
}catch(PDOException $e){
    echo "Connection failed: " . $e->getMessage();
}

Create a Short URL with PHP

The following code will make code and generates a short URL with a custom URL Shortener class using PHP and MySQL.

  • Initialize the Shortener class and pass the PDO object.
  • Specify the long URL.
  • Specify the short URL prefix. If you want to use RewriteEngine to Rewrite the URL, specify only the base URI. Otherwise, specify the base URI with a query string to pass the short code.
  • Call the urlToShortCode() function to get the short code of the long URL.
  • Create a short URL with URI prefix and short code.
// Include database configuration file
require_once 'dbConfig.php';

// Include URL Shortener library file
require_once 'Shortener.class.php';

// Initialize Shortener class and pass PDO object
$shortener = new Shortener($db);

// Long URL
$longURL = 'https://www.codexworld.com/tutorials/php/';

// Prefix of the short URL 
$shortURL_Prefix = 'https://xyz.com/'; // with URL rewrite
$shortURL_Prefix = 'https://xyz.com/?c='; // without URL rewrite

try{
    // Get short code of the URL
    $shortCode = $shortener->urlToShortCode($longURL);
    
    // Create short URL
    $shortURL = $shortURL_Prefix.$shortCode;
    
    // Display short URL
    echo 'Short URL: '.$shortURL;
}catch(Exception $e){
    // Display error
    echo $e->getMessage();
}

Redirect to Long URL

The given code handles the redirection from a short URL to the original URL.

  • Firstly, retrieve the short code from the query string of the URL.
  • Secondly, To get the long URL by the short code, you have to call shortCodeToUrl() function.
  • Thirdly, redirect the user to the original URL.
// Include database configuration file
require_once 'dbConfig.php';

// Include URL Shortener library file
require_once 'Shortener.class.php';

// Initialize Shortener class and pass PDO object
$shortener = new Shortener($db);

// Retrieve short code from URL
$shortCode = $_GET["c"];

try{
    // Get URL by short code
    $url = $shortener->shortCodeToUrl($shortCode);
    
    // Redirect to the original URL
    header("Location: ".$url);
    exit;
}catch(Exception $e){
    // Display error
    echo $e->getMessage();
}

URL Rewrite with HTACCESS

Use HTACCESS with RewriteEngine to make the URL user-friendly. Also, build a .htaccess file and add the following code.

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9]+)/?$ redirect.php?c=$1 [L] 
</IfModule>

SEE ALSO: Add WYSIWYG HTML Editor to Textarea with CKEditor

Conclusion

Firstly, our Shortener class will offer you to make a short URL easily with the help of PHP. So, you can use this library to figure your own URL Shortener with MySQL and PHP. Secondly, use the sample code to shorten the URL on the fly without using any third-party service. At last, the PHP URL Shortener class can effortlessly be protracted to customize the URL shorting functionality.

Also, read our previos blog- Auto Resize Textarea Height using jQuery

Tags: PHP URL ShortenerShort URL
ShareTweetSendShareSharePinScan
Lakshika Mathur

Lakshika Mathur

Related Posts

What is Application Programming Interface (APIs), Types, and Importance.
PHP and MySQL

What is Application Programming Interface (APIs)?

January 29, 2022
61
Like Dislike Rating System with jQuery, Ajax, and PHP
jQuery & AJAX

Like Dislike Rating System with jQuery, Ajax, and PHP

January 6, 2020
739
Star Rating System with jQuery, Ajax, PHP, and MySQL
jQuery & AJAX

Star Rating System with jQuery, Ajax, PHP, and MySQL

January 6, 2020
162
How to Force Download File in PHP
PHP and MySQL

How to Force Download File in PHP

January 2, 2020
82
How to Connect to the Remote MySQL Database using PHP
PHP and MySQL

How to Connect to the Remote MySQL Database using PHP

January 1, 2020
28
How to Generate QR Code with PHP using Google Chart API
PHP and MySQL

How to Generate QR Code with PHP using Google Chart API

January 1, 2020
83
Next Post
jQuery UI Autocomplete with Images and Custom HTML in PHP

jQuery UI Autocomplete with Images and Custom HTML in PHP

Verify Email Address and Check if Email is Real using PHP

Verify Email Address and Check if Email is Real using PHP

Leave a Reply Cancel reply

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

Categories

  • Comparison (3)
  • HTML & CSS (9)
  • Interesting Facts (1)
  • JavaScript (27)
    • jQuery & AJAX (18)
  • PHP and MySQL (48)
  • Security (10)
  • SEO (2)
  • Trademark (2)
  • Tutorials (5)
  • Uncategorized (1)
  • Web Hosting (19)
    • VPS Server (5)
  • WordPress (8)

Recent Posts

  • Is the Trademark valuable to your Brand or domain?
  • Ideas For Ten Fantastic Online Business From Home
  • Some best free WordPress Themes for Affiliate Marketing Websites
  • Home
  • Posts
  • Privacy Policy
  • Terms and Conditions

Built and Maintained With ♥ by AllsWeb Team

No Result
View All Result
  • Home
  • Main Home
  • PHP and MySQL
  • JavaScript
    • jQuery & AJAX
  • WordPress
  • SEO
  • Web Hosting
  • Comparison

Built and Maintained With ♥ by AllsWeb Team

Go to mobile version