Steps to be followed to create php class and database and generate shorturl and decode shorturl to original when needed.
Step1: Create Database using SQL
CREATE TABLE IF NOT EXISTS short_urls_QueryHome (
id INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
long_url VARCHAR(255) NOT NULL,
short_code VARBINARY(6) NOT NULL,
date_created INTEGER UNSIGNED NOT NULL,
counter INTEGER UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (id),
KEY short_code (short_code)
)
ENGINE=InnoDB;
step2: Create short code here is php class for short code of URL's name it as ShortUrl.php
<?php
class ShortUrl
{
protected static $chars = "123456789bcdfghjkmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ";
protected static $table = "short_urls_QueryHome";
protected static $checkUrlExists = true;
protected $pdo;
protected $timestamp;
public function __construct(PDO $pdo) {
$this->pdo = $pdo;
$this->timestamp = $_SERVER["REQUEST_TIME"];
}
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) {
$id = $this->insertUrlInDb($url);
$shortCode = $this->convertIntToShortCode($id);
$this->insertShortCodeInDb($id, $shortCode);
return $shortCode;
}
protected function insertUrlInDb($url) {
$query = "INSERT INTO " . self::$table .
" (long_url, date_created) " .
" VALUES (:long_url, :timestamp)";
$stmnt = $this->pdo->prepare($query);
$params = array(
"long_url" => $url,
"timestamp" => $this->timestamp
);
$stmnt->execute($params);
return $this->pdo->lastInsertId();
}
protected function convertIntToShortCode($id) {
$id = intval($id);
if ($id < 1) {
throw new Exception(
"The ID is not a valid integer");
}
$length = strlen(self::$chars);
// make sure length of available characters is at
// least a reasonable minimum - there should be at
// least 10 characters
if ($length < 10) {
throw new Exception("Length of chars is too small");
}
$code = "";
while ($id > $length - 1) {
// determine the value of the next higher character
// in the short code should be and prepend
$code = self::$chars[fmod($id, $length)] .
$code;
// reset $id to remaining value to be converted
$id = floor($id / $length);
}
// remaining value of $id is less than the length of
// self::$chars
$code = self::$chars[$id] . $code;
return $code;
}
protected function insertShortCodeInDb($id, $code) {
if ($id == null || $code == null) {
throw new Exception("Input parameter(s) invalid.");
}
$query = "UPDATE " . self::$table .
" SET short_code = :short_code WHERE id = :id";
$stmnt = $this->pdo->prepare($query);
$params = array(
"short_code" => $code,
"id" => $id
);
$stmnt->execute($params);
if ($stmnt->rowCount() < 1) {
throw new Exception(
"Row was not updated with short code.");
}
return true;
}
createShortCode() delegates the following tasks to specific methods:
insertUrlInDb() to insert the long URL into the database and return the new row’s ID.
convertIntToShortCode() to convert the new row’s ID to our base-50 number scheme.
insertShortCodeInDb() to update the row with the newly created short code.
step3: then this php code will insert url into database then generates its short url and again save this short url to database.
<?php
include "../include/config.php";
include "../include/ShortUrl.php";
try {
$pdo = new PDO(DB_PDODRIVER . ":host=" . DB_HOST .
";dbname=" . DB_DATABASE,
DB_USERNAME, DB_PASSWORD);
}
catch (PDOException $e) {
trigger_error("Error: Failed to establish connection to database.");
exit;
}
$shortUrl = new ShortUrl($pdo);
try {
$code = $shortUrl->urlToShortCode($_POST["url"]);
printf('<p><strong>Short URL:</strong> <a href="%s">%1$s</a></p>',
SHORTURL_PREFIX . $code);
exit;
}
catch (Exception $e) {
// log exception and then redirect to error page.
header("Location: /error");
exit;
}
Step4: it will validate the shortcode url and get original long url from database.
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) {
return preg_match("|[" . self::$chars . "]+|", $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 counter = counter + 1 WHERE id = :id";
$stmt = $this->pdo->prepare($query);
$params = array(
"id" => $id
);
$stmt->execute($params);
}
}
The code to decode a short code and obtain the long URL is part of the ShortUrl class too. We call the shortCodeToUrl() method and pass it the short code we have extracted from the URI. shortCodeToUrl() also accepts an optional parameter, $increment, which defaults to true. It then delegates the following:
validateShortCodeFormat() makes sure that the provided short code only contains letters and numbers.
getUrlFromDb() queries the database for the supplied short code and returns the record’s id, long_url, and counter fields.
If the $increment parameter is true, incrementCounter() is called to increment the row’s counter field.
Reference: http://www.sitepoint.com/building-your-own-url-shortener/