create short url php

How to create a Shortlink using PHP

create short url php
How to create a Shortlink using PHP

How to create a URL Shortener using PHP – Short links are always a recommended method for sharing links. Easy to remember and can be shared easily on the web. Many available URL Shortener services allow you to convert long URLs to short URLs. But the main drawback of the service is that you won’t be able to use your domain on its short link. If you want to create a URL Shortener with your domain, you need to create your URL Shortener.

The URL Shortener service requires a long URL and compressing it in short links/links that are easier to share. You can programmatically create Short URLs using PHP without any third-party URL Shortener API. In this tutorial, I would love a tutorial on how to build a library URL Shortener and create a Shortener URL using PHP and MySQL. With the PHP URL Shortener library, You can shorten the long URL and use your domain on its short link.

In this example, the script demonstrates the process of creating a clean and short link that can easily be shared by email or social media. The Database used to store information about long and short URLs. You can also track the number of clicks visitor has obtained shorter URLs.

Creating a Database Table

We will use the Database to handle redirection/redirect based on the shortcode. The following SQL creates a table tb_short_url in the MySQL database to store URL info (original_url, short_code, hits, and time added).

READ  How to move Directory Folder Downloads in Disk C to Local Disk D
CREATE TABLE `tb_short_url` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `original_url` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
 `short_code` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
 `hits` int(11) NOT NULL,
 `ditambahkan` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Library URL Shortener (Shortener. Class. PHP)

The URL Shortener Class allows creating short URLs programmatically using PHP and MySQL. This Class uses the PDO extension to work with the MySQL database, so the PDO object instance required on the Shortener class initialization.

Static variables:

  • $chars – Characters entered in the shortcode. (Group of characters separated by |).
  • $table – The database table name for storing URLs and shortcodes.
  • $checkUrlExists – Set to TRUE, to check if the original URL already exists.
  • $codeLength – Shortcode character length.

Function:

  • __construct () – Set the PDO object reference and timestamp.
  • urlToShortCode() – Validates the URL and creates a shortcode.
  • validateUrlFormat () – Validates the URL format.
  • verifyUrlExists () – verifies whether the URL already exists or has not used cURL in PHP.
  • urlExistsInDB () – Checks if a long URL already exists in the Database.
  • createShortCode () – Creates a shortcode for the long URL and inserts a long URL & shortcodes into the Database.
  • generateRandomString () – Generates a random string (shortcode) with the character specified in the variable $chars.
  • insertUrlInDB () – Enters the URL into the database using PDO and MySQL extensions.
  • shortCodeToUrl () – Converts the shortcode into long URLs and inserts the number of hits in the Database.
  • validateShortCode () – Validates the shortcode based on allowed characters.
  • getUrlFromDB () – Retrieves the long URL from the Database based on the shortcode.
  • incrementCounter () – Added a URL visit counter in the Database.
   return (!empty($response) && $response != 404);
    }
    protected function urlExistsInDB($url){
        $query = "SELECT short_code FROM ".self::$table." WHERE original_url = :original_url LIMIT 1";
        $stmt = $this->pdo->prepare($query);
        $params = array(
            "original_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." (original_url, short_code, added) VALUES (:original_url, :short_code, :timestamp)";
        $stmnt = $this->pdo->prepare($query);
        $params = array(
            "original_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 given.");
        }
        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 not found.");
        }
        if($increment == true){
            $this->incrementCounter($urlRow["id"]);
        }
        return $urlRow["original_url"];
    }
    protected function validateShortCode($code){
        $rawChars = str_replace('|', '', self::$chars);
        return preg_match("|[".$rawChars."]+|", $code);
    }
    protected function getUrlFromDB($code){
        $query = "SELECT id, original_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);
    }
}

Configuration Database (dbConfig. php)

READ  How to Uninstall Chromium On Windows 10

In the dbConfig. php file, PDO (PHP Data Objects) is used to connect and select the database. Specify the host database ($hostDB), username ($usernameDB), password ($passwordDB), and database name ($DBname) according to your MySQL database server credentials.

<?php
$hostDB     = "localhost";
$usernameDB = "root";
$passwordDB = "";
$DB name    = "algoritmcomputer";
// Create a database connection
try{
    $db = new PDO("mysql:host=$hostDB;dbname=$namaDB", $usernameDB, $passwordDB);
}catch(PDOException $e){
    echo "Database connection Failed: " . $e->getMessage();
}

Creating URL Shortener with PHP

The following code creates a short system and generates a short URL with the URL Shortener Class using PHP and MySQL.

  1. Initialize the Shortener class and forward it to PDO.
  2. Specify the long URL you want to convert in a short URL.
  3. Specifies a shortened URL prefix. If you want to use RewriteEngine to rewrite the URL, specify only the base URI. Otherwise, specify the base URI with the query-string (? c =).
  4. Call the urlToShortCode () function to obtain a shortcode from a long URL.
  5. Create a short URL with the URI prefix and shortcode.
// Include Database configuration files
require_once 'dbConfig.php';
// Include the URL library Shortener file
require_once 'Shortener.class.php';
// Initializing the Shortener class and forwarding it to PDO
$shortener = new Shortener($db);
// Original URL
$longURL = $_POST['longurl'];;
// Prefix of Short URLS
$shortURL_Prefix = 'http://localhost/shorten/s/'; // With rewrite URL
//$shortURL_Prefix = 'http://localhost/shorten/s/?c='; // Without rewrite URL
try{
    // Getting URLS with short code
    $shortCode = $shortener->urlToShortCode($longURL);
    // Creating a short URL
    $shortURL = $shortURL_Prefix.$shortCode;
    // Displaying short URLS
    echo 'Short URL: '.$shortURL;
}catch(Exception $e){
    // Display errors
    echo $e->getMessage();
}

Redirect to the original URL

The following code handles redirects from a short URL to the original URL.

// Include Database configuration files
require_once '../dbConfig.php';
// Include the URL library Shortener file
require_once '../Shortener.class.php';
// Initializing the Shortener class and forwarding it to PDO
$shortener = new Shortener($db);
// Retrieving a short code URL
$shortCode = $_GET["c"];
try{
    // Getting URLS with short code
    $url = $shortener->shortCodeToUrl($shortCode);
    // Redirect to the original URL
    header("Location: ".$url);
    exit;
}catch(Exception $e){
    // Display errors
    echo $e->getMessage();
}

Rewrite URL in .htaccess

If you want to create a URL without a query-string, use HTACCESS with RewriteEngine. Create a .htaccess file and add the following code. Make sure the mod_rewrite module is active on your server.

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

That’s How to create a URL Shortener using PHP easiest by AlgoritmComputer.com, share this article if useful.

Leave a Reply

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