A short URL is usually a good method to convey the URL of a web page. It is simple to remember and may be simply shared on the internet. There are several URL Shortener services that allow you to convert lengthy URLs to short URLs online. However, one of the primary downsides of these services is that you will be unable to utilise your own domain in the short URL. You must use a custom URL Shortener if you wish to produce a short URL with your own domain name.
The URL Shortener service compresses a lengthy URL into a short link that is simpler to share. Without the use of a third-party URL Shortener API, you may produce short URLs programmatically using PHP. In this tutorial, we will demonstrate how to develop a URL Shortener library and short URLs with PHP and MySQL. You may use the PHP URL Shortener package to shorten lengthy URLs and utilise your own domain in the short URLs.
The demo script demonstrates how to produce a clean, concise, and compact link that can be simply shared via email or social media. The database stores information on long and short URLs. You may also track how many visitors click on the short URL.
The database will be used to manage the redirection depending on the shortcode. The SQL below creates a short urls table in the MySQL database to hold URL information (long URL, short code, hits, and create time).
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 you to produce short URLs automatically using PHP and MySQL. Because this method uses the PDO Extension to interact with the MySQL database, a PDO data object is required upon Shortener class startup.
Static Variables:
- $chars
– Letters for the unique code are accepted. (The letters set is separated by |)
- $table
– The name of the database table that will hold the URL and short code information.
- $checkUrlExists
– Set to TRUE to see if the lengthy URL exists.
- $codeLength
– The number of characters in the short code.
Functions:
- __construct() – PDO object address and timing are set.
- urlToShortCode() – Validate the URL and generate a short code.
- validateUrlFormat() – Validate the URL's format.
- verifyUrlExists() – Using cURL in PHP, check whether the URL exists or not.
- urlExistsInDB() – Check to see if the lengthy URL exists in the database. If the shot code exists, return it; otherwise, return FALSE.
- createShortCode() – Make a short number for the long URL and save both the long URL and the short codes in the data.
- generateRandomString() – Generate a random string (short code) using the characters supplied in the $chars variable.
- insertUrlInDB() – PDO Extension and MySQL are used to insert URL information into the database and retrieve the row ID.
- shortCodeToUrl() – Transform the short code to a long URL and enter the number of hits into the database.
- validateShortCode() – Verify the short code using the permitted characters.
- getUrlFromDB() – Based on the short code, retrieve the full URL from the database.
- incrementCounter() – In the database, boost the URL visits counter for a certain entry.
<?php /** * Class to create short URLs and decode shortened URLs * * @author CodexWorld.com <[email protected]> * @copyright Copyright (c) 2018, CodexWorld.com * @url https://www.codexworld.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); } }
PDO (PHP Data Objects) is used in the dbConfig.php file to connect to and choose the database. As per your MySQL database server credentials, provide the database host ($dbHost), username ($dbUsername), password ($dbPassword), and name ($dbName).
<?php // Database configuration $dbHost = "localhost"; $dbUsername = "root"; $dbPassword = "root"; $dbName = "codexworld"; // Create database connection try{ $db = new PDO("mysql:host=$dbHost;dbname=$dbName", $dbUsername, $dbPassword); }catch(PDOException $e){ echo "Connection failed: " . $e->getMessage(); }
Using PHP and MySQL, the following code constructs short code and generates short URLs with a custom URL Shortener class.
- Create the Shortener class and provide it the PDO object.
- Enter the lengthy URL to be converted into a short link.
- Enter the short URL prefix. Only mention the base URI if you wish to use - - - - RewriteEngine to rewrite the URL. To pass the short code, give the base URI followed by a query string.
- To acquire the short code of a large URL, use the urlToShortCode() method.
Create a short URL using the URI prefix and the 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(); }
The code below handles the redirection from the short URL to the original URL.
- Retrieve the short code from the URL's query string or the URI segment.
- To obtain the long URL from the short code, use the shortCodeToUrl() method.
- Redirect the user back 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(); }
Use HTACCESS with RewriteRule to make the URL more user-friendly. You may use mod rewrite to make URLs shorter and easier to distribute.
Add the following code to a .htaccess file.
<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>
The HTACCESS RewriteRule mentioned above will route the request to the redirect.php file. As a result, the name of the redirect.php file does not need to be included in the short URL.
- The short URL without HTACCESS is as follows: https://example.com/redirect.php?c=gzYN7BK
- The short URL with HTACCESS looks like this: https://example.com/gzYN7BK
Our Shortener class makes it simple to build short URLs in PHP. This library may be used to create your own URL Shortener using PHP and MySQL. Use the example code to quickly shorten a URL without relying on a third-party service. Furthermore, the PHP URL Shortener class is simply extendable to personalise the URL shortening features.
© ThemesGiant Copyright @2015-2022 | All rights reserved.