Short Link Generator in PHP Php by Rajesh Kumar Sahanee - March 28, 2020March 28, 20200 Post Views: 15,257 Hello friends, today we are going to see a code for short link generator in php. I am sharing this code specially on the suggestion of one of my friend. You may have already know bitly and tinyurl most popular for url shortening service. The same concept is behind this code also. If you want to provide same service like bitly and tinyurl then just book a domain and host this code. Before start coding we need to create database and table. You can create database with any name of your choice then select it and execute below sql query and its done. database.sql MySQL CREATE TABLE `links` ( `id` bigint(20) NOT NULL PRIMARY KEY AUTO_INCREMENT, `slug` varchar(15) NOT NULL UNIQUE, `url` varchar(512) NOT NULL UNIQUE, `created` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `hits` bigint(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 1234567 CREATE TABLE `links` ( `id` bigint(20) NOT NULL PRIMARY KEY AUTO_INCREMENT, `slug` varchar(15) NOT NULL UNIQUE, `url` varchar(512) NOT NULL UNIQUE, `created` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `hits` bigint(20) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; Now the coding part config.php config.php PHP <?php define('MYSQL_HOST', 'localhost'); define('MYSQL_USER', 'root'); define('MYSQL_PASSWORD', ''); define('MYSQL_DATABASE', 'test'); define('SITE_URL', 'http://localhost/url-shortener/'); //your website url i.e https://zatackcoder.com ?> 12345678910 <?php define('MYSQL_HOST', 'localhost');define('MYSQL_USER', 'root'); define('MYSQL_PASSWORD', ''); define('MYSQL_DATABASE', 'test'); define('SITE_URL', 'http://localhost/url-shortener/'); //your website url i.e https://zatackcoder.com ?> Here replace root with your database username, test with your database name and paste your password in empty string as in my case i have not setup password that’s why it is empty string. shorten.php shorten.php PHP <?php require 'config.php'; header('Content-Type: text/plain;charset=UTF-8'); $url = isset($_REQUEST['url']) ? urldecode(trim($_REQUEST['url'])) : ''; if (!preg_match('/[a-zA-Z0-9]+\.[a-zA-Z0-9]+$/', $url)) { die('Error'); } //add http if not already in url if (!preg_match("~^(?:f|ht)tps?://~i", $url)) { $url = "http://" . $url; } function nextLetter(&$str) { $str = ('z' == $str ? 'a' : ++$str); } function getNextSlug($s) { $a = str_split($s); $c = count($a); if (preg_match('/^z*$/', $s)) { // string consists entirely of `z` return str_repeat('a', $c + 1); } while ('z' == $a[--$c]) { nextLetter($a[$c]); } nextLetter($a[$c]); return implode($a); } $db = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE); $url = $db->real_escape_string($url); $result = $db->query("SELECT slug FROM links WHERE url = '{$url}' LIMIT 1"); if ($result && $result->num_rows > 0) { // If there’s already a short URL for this URL die(SITE_URL . $result->fetch_object()->slug); } else { $result = $db->query('SELECT slug, url FROM links ORDER BY id DESC, slug DESC LIMIT 1'); $slug = ($result && $result->num_rows > 0) ? getNextSlug($result->fetch_object()->slug) : 'a'; if ($db->query("INSERT INTO links (slug, url, created, hits) VALUES ('{$slug}', '{$url}', NOW(), '0')")) { header('HTTP/1.1 201 Created'); echo SITE_URL . $slug; $db->query('OPTIMIZE TABLE `links`'); } } ?> 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849 <?php require 'config.php'; header('Content-Type: text/plain;charset=UTF-8'); $url = isset($_REQUEST['url']) ? urldecode(trim($_REQUEST['url'])) : '';if (!preg_match('/[a-zA-Z0-9]+\.[a-zA-Z0-9]+$/', $url)) { die('Error');}//add http if not already in urlif (!preg_match("~^(?:f|ht)tps?://~i", $url)) { $url = "http://" . $url;} function nextLetter(&$str) { $str = ('z' == $str ? 'a' : ++$str);} function getNextSlug($s) { $a = str_split($s); $c = count($a); if (preg_match('/^z*$/', $s)) { // string consists entirely of `z` return str_repeat('a', $c + 1); } while ('z' == $a[--$c]) { nextLetter($a[$c]); } nextLetter($a[$c]); return implode($a);} $db = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE); $url = $db->real_escape_string($url); $result = $db->query("SELECT slug FROM links WHERE url = '{$url}' LIMIT 1");if ($result && $result->num_rows > 0) { // If there’s already a short URL for this URL die(SITE_URL . $result->fetch_object()->slug);} else { $result = $db->query('SELECT slug, url FROM links ORDER BY id DESC, slug DESC LIMIT 1'); $slug = ($result && $result->num_rows > 0) ? getNextSlug($result->fetch_object()->slug) : 'a'; if ($db->query("INSERT INTO links (slug, url, created, hits) VALUES ('{$slug}', '{$url}', NOW(), '0')")) { header('HTTP/1.1 201 Created'); echo SITE_URL . $slug; $db->query('OPTIMIZE TABLE `links`'); }}?> code to make url short index.php index.php PHP <?php require 'config.php'; if (isset($_GET['slug'])) { $url = SITE_URL; $slug = preg_replace('/[^a-z0-9]/si', '', $_GET['slug']); $db = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE); $escapedSlug = $db->real_escape_string($slug); $results = $db->query("SELECT url FROM links WHERE slug = '{$escapedSlug}'"); if ($results && $results->num_rows > 0) { $db->query("UPDATE links SET hits = hits + 1 WHERE slug = '{$escapedSlug}'"); $url = $results->fetch_object()->url; } $db->close(); header('Location: ' . $url, null, 301); } ?> <html> <body> <form action="shorten.php"> <input type="text" name="url" placeholder="Enter a long URL to make it short"/> <input type="submit" value="Short It"/> </form> </body> </html> 12345678910111213141516171819202122232425262728 <?phprequire 'config.php'; if (isset($_GET['slug'])) { $url = SITE_URL; $slug = preg_replace('/[^a-z0-9]/si', '', $_GET['slug']); $db = new mysqli(MYSQL_HOST, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DATABASE); $escapedSlug = $db->real_escape_string($slug); $results = $db->query("SELECT url FROM links WHERE slug = '{$escapedSlug}'"); if ($results && $results->num_rows > 0) { $db->query("UPDATE links SET hits = hits + 1 WHERE slug = '{$escapedSlug}'"); $url = $results->fetch_object()->url; } $db->close(); header('Location: ' . $url, null, 301);}?><html> <body> <form action="shorten.php"> <input type="text" name="url" placeholder="Enter a long URL to make it short"/> <input type="submit" value="Short It"/> </form> </body></html> code to process short url .htaccess .htaccess Apache RewriteEngine On RewriteBase /url-shortener RewriteRule ^shorten(.*)$ shorten.php?$1 [L,QSA] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?slug=$1 [L,QSA] 123456 RewriteEngine OnRewriteBase /url-shortener RewriteRule ^shorten(.*)$ shorten.php?$1 [L,QSA]RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteRule ^(.*)$ index.php?slug=$1 [L,QSA] Rewrite rules to bring all the request to index.php to process short url and to access shorten.php to short url with and without .php extension. Here RewriteBase /url-shortener can be replace with / if you are hosting it on main domain instead of sub-folder in my case. Screenshots NetBeans Project Download Short Link Generator NetBeans Project 1 file(s) 4.46 KB Download Thanks friends Please don’t forget to share