Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active December 26, 2023 18:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/a01374d9f6fb13d5e71ac4fd6f06725f to your computer and use it in GitHub Desktop.
Save code-boxx/a01374d9f6fb13d5e71ac4fd6f06725f to your computer and use it in GitHub Desktop.
PHP MYSQL URL Shortener

PHP MYSQL URL SHORTENER

https://code-boxx.com/url-shortener-php-mysql/

NOTES

  1. RENAME 3b-htaccess.txt to .htaccess. Tested on an Apache server only – IIS and NGINX users, translate your own .htaccess.
  2. If not deployed at root, edit .htaccess. For example, http:/site.com/GO/ - Change to RewriteBase /GO/ and RewriteRule /GO/ 3c-index.php [L]
  3. Create a database and import 1-database.sql.
  4. Change the database settings 2-lib-shorten.php to your own.
  5. Access 3a-dummy.php to generate a dummy shortcode.
  6. That's all. Access http://site.com/SHORTCODE and it should redirect.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

CREATE TABLE `short_url` (
`short` varchar(16) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
`full` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `short_url`
ADD PRIMARY KEY (`short`),
ADD UNIQUE KEY `full` (`full`);
<?php
class Shorten {
// (A) CONSTRUCTOR - CONNECT TO THE DATABASE
private $pdo = null;
private $stmt = null;
public $error;
function __construct () {
$this->pdo = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHAR,
DB_USER, DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
}
// (B) DESTRUCTOR - CLOSE DATABSE CONNECTION
function __destruct () {
if ($this->stmt !== null) { $this->stmt = null; }
if ($this->pdo !== null) { $this->pdo = null; }
}
// (C) HELPER - EXECUTE SQL QUERY
function exec ($sql, $data=null) : void {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
}
// (D) HELPER - RANDOM STRING
// CREDITS: https://stackoverflow.com/questions/4356289/php-random-string-generator
function random ($length=6) {
$char = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_.~";
$clen = strlen($char);
$rand = "";
for ($i=0; $i<$length; $i++) { $rand .= $char[rand(0, $clen-1)]; }
return $rand;
}
// (E) GET BY SHORT URL CODE
function getShort ($short) {
$this->exec("SELECT `full` FROM `short_url` WHERE `short`=?", [$short]);
return $this->stmt->fetchColumn();
}
// (F) GET BY FULL URL
function getFull ($full) {
$this->exec("SELECT `short` FROM `short_url` WHERE `full`=?", [$full]);
return $this->stmt->fetchColumn();
}
// (G) DELETE ENTRY
function del ($short) {
$this->exec("DELETE FROM `short_url` WHERE `url_id`=?", [$short]);
return true;
}
// (H) GENERATE A NEW SHORT URL CODE
function create ($full) {
// (H1) CHECK IF FULL URL ALREADY EXIST
if ($this->getFull($full)!="") {
$this->error = "$full is already defined.";
return false;
}
// (H2) GENERATE RANDOM SHORT CODE
$short = null;
while ($short === null) {
$random = $this->random();
if ($this->getShort($random) == "") { $short = $random; }
}
// (H3) INSERT ENTRY
$this->exec(
"INSERT INTO `short_url` (`short`, `full`) VALUES (?,?)",
[$short, $full]
);
return $short;
}
}
// (I) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHAR", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
// (J) INIT
$_SURL = new Shorten();
<?php
// (A) ADD ENTRIES
require "2-lib-shorten.php";
$short = $_SURL->create("https://code-boxx.com");
echo $short==false ? $_SURL->error : $short;
// (B) TO DELETE
// echo $_SURL->del(SHORT) ? "OK" : $_SURL->error ;
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^3c-index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /3c-index.php [L]
<?php
// (A) GET SHORT URL CODE
$short = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
$short = explode("/", trim($short, "/"));
$short = count($short)==1 ? $short[0] : null ;
$full = null;
// (B) GET FULL URL
if ($short!==null) {
require "2-lib-shorten.php";
$full = $_SURL->getShort($short);
}
// (C) REDIRECT IF VALID
if ($full!==false) { header("Location: $full"); }
else { echo "INVALID REQUEST"; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment