PHP Classes

Custom PHP URL Shortener using PDO: Create and expand short URLs in a custom domain

Recommend this page to a friend!
  Info   View files Example   View files View files (6)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog (1)    
Ratings Unique User Downloads Download Rankings
Not yet rated by the usersTotal: 169 All time: 8,852 This week: 68Up
Version License PHP version Categories
urlshortner 1.0.0The PHP License5HTTP, PHP 5


This class can create and expand short URLs in a custom domain.

It can take a given URL as a parameter and store that URL and a short URL code in a database accessed using PDO.

The class takes a previously initialized PDO object to work with MySQL and other databases supported by PDO.

The class can return the short URL code as part of a short URL of a page that a PHP can serve from a custom domain.

When the user browser accesses the short URL page, the class can return the original long URL, so a script that uses the type can redirect the user browser to the original long URL page.

The class can also track the number of hits the short URL gets by the visitors.

Innovation Award
PHP Programming Innovation award nominee
October 2021
Number 5
URL shorteners are helpful to allow the users to create shorter versions of a given URL that are easier to type.

Usually, URL shorter components use a database to store the long and faster versions of a URL.

This class uses the PHP PDO extension to access a database that stores the short URL information. This possibility allows developers to use many types of SQL-based databases to benefit from this component.

Manuel Lemos
Picture of anas khan
  Performance   Level  
Name: anas khan <contact>
Classes: 1 package by
Country: India India
Age: ???
All time rank: 4235292 in India India
Week rank: 275 Up19 in India India Up
Innovation award
Innovation award
Nominee: 1x


// Include database configuration file
require_once 'config.php';

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

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

// Long URL
$longURL = '';

// Prefix of the short URL
$shortURL_Prefix = ''; // with URL rewrite
$shortURL_Prefix = ''; // without URL rewrite

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



Custom URL shortner, create short URL with your own domain name. This script creates a clean, short, and tiny link that can be shared easily via email or social media. The database is used to store the information about long and short URL. Also, you can track the number of hits the short URL gets by the visitors.

URL Shortener Library (class.URLShortener.php) The URL Shortener class allow to programmatically create short URL using PHP and MySQL. This class uses PDO Extension to work with the MySQL database, so, PDO object instance is required on initialization of URLShortener class.

Static Variables: <ul> <li>$characters &ndash; Allowed characters for the short code. (Characters group is separated by |)</li> <li>$tbl_name &ndash; Database table name to store the URL and short code info.</li> <li>$ifURLExists &ndash; Set to TRUE, to check whether the long URL exists.</li> <li>$codeLength &ndash; The length of the short code characters.</li> </ul>


<ul> <li>__construct() &ndash; Set PDO object reference and timestamp.</li> <li>urlToShortCode() &ndash; Validate URL and create short code.</li> <li>validateUrlFormat() &ndash; Validate the format of the URL.</li> <li>verifyUrlExists() &ndash; Verify the URL whether it exist or not using cURL in PHP.</li> <li>urlExistsInDB() &ndash; Check whether the long URL is exist in the database. If exist, return the shot code, otherwise, return FALSE.</li> <li>createShortCode() &ndash; Create short code for the long URL and insert the long URL &amp; short code in the database.</li> <li>generateRandomString() &ndash; Generate random string (short code) with the specified characters in the $chars variable.</li> <li>insertUrlInDB() &ndash; Insert URL info in the database using PDO Extension and MySQL and return the row ID.</li> <li>shortCodeToUrl() &ndash; Convert the short code to long URL and insert the hits count in the database.</li> <li>validateShortCode() &ndash; Validate the short code based on the allowed characters.</li> <li>getUrlFromDB() &ndash; Fetch the long URL from the database based on the short code.</li> <li>incrementCounter() &ndash; Increment the URL visits counter in the database for a particular record.</li> </ul>

URL Rewrite with HTACCESS If you want to make the URL user-friendly, use HTACCESS with RewriteRule. With mod_rewrite, you can make the URL length shorter and easy to share.

Create 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> The above HTACCESS RewriteRule will send the request to redirect.php file. So, the redirect.php file name doesn?t need to mention in the short URL.

The short URL without using HTACCESS looks something like this ? The short URL with using HTACCESS looks something like this ?

  Files folder image Files  
File Role Description
Plain text file class.URLShortner.php Class Class source
Accessible without login Plain text file config.php Example Example script
Accessible without login Plain text file database.sql Data Auxiliary data
Accessible without login Plain text file index.php Example Example script
Accessible without login Plain text file Doc. Documentation
Accessible without login Plain text file redirect.php Example Example script

 Version Control Unique User Downloads Download Rankings  
This week:0
All time:8,852
This week:68Up