how to make url shortener in php & MySQL?

how to make url shortener in php? Learn how to create a custom URL shortener in PHP. This custom URL shortener can can be created in a some times. free Source code download included!

how to make url shortener in php

Best PHP URL Shortener Scripts – Create the database table structure & Create Short URL using PHP URL Shortener. Also Read : Get The Full URL

Step 1 : Create Database Table

makes a short_urls table in the MySQL database
how to make url shortener in php with mysql Database.

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;

URL Shortener Library

Shortener.class.php
how to make url shortener in php?

 
 * @copyright Copyright (c) 2017, pakainfo.com
 * @url https://www.pakainfo.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 urlToshorterNum($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.");
            }
        }

        $shorterNum = $this->urlExistsInDB($url);
        if($shorterNum == false){
            $shorterNum = $this->createshorterNum($url);
        }

        return $shorterNum;
    }

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

    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 shorterNumToUrl($code, $increment = true){
        if(empty($code)) {
            throw new Exception("No short code was supplied.");
        }

        if($this->validateshorterNum($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 validateshorterNum($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);
    }
}

Database Configuration

conDb.php

getMessage();
}

Create Short URL with PHP

require_once 'conDb.php';

require_once 'Shortener.class.php';

$shortener = new Shortener($db);

$longURL = 'https://www.pakainfo.com/tutorials/php/';
 
$shortURL_Prefix = 'https://new-domain.com/'; // with URL rewrite
$shortURL_Prefix = 'https://new-domain.com/?c='; // without URL rewrite

try{
    $shorterNum = $shortener->urlToshorterNum($longURL);
    
    $shortURL = $shortURL_Prefix.$shorterNum;
    
    echo 'Short URL: '.$shortURL;
}catch(Exception $e){
    echo $e->getMessage();
}

Redirect to Long URL

require_once 'conDb.php';

require_once 'Shortener.class.php';

$shortener = new Shortener($db);

$shorterNum = $_GET["c"];

try{
    $url = $shortener->shorterNumToUrl($shorterNum);
    
    header("Location: ".$url);
    exit;
}catch(Exception $e){
    echo $e->getMessage();
}

URL Rewrite with HTACCESS

Create a .htaccess file and add the following code.


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

A simple URL shortener for PHP
how to make url shortener in php?
without using HTACCESS – https://domain-name.com/redirect.php?c=gzYN7BK
with using HTACCESS – https://domain-name.com/gzYN7BK

Example : https://infinityknow.com/php-laravel-get-current-url-example/

Leave a Comment