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.
1 2 3 4 5 6 7 |
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
1 2 3 4 5 6 7 8 9 10 |
<?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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
<?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`'); } } ?> |
code to make url short
index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?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> |
code to process short url
.htaccess
1 2 3 4 5 6 |
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] |
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
Thanks friends
Please don’t forget to share
Comments