Last active
December 22, 2017 11:10
-
-
Save jcubic/21c83082a9ec0c1e7b70dfc362050e9c to your computer and use it in GitHub Desktop.
Simple url shortener in php and sqlite
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
RewriteEngine on | |
RewriteCond %{SCRIPT_FILENAME} !-f | |
RewriteCond %{SCRIPT_FILENAME} !-d | |
RewriteRule (.*) /index.php?$1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
header('Content-Type: text/plain'); | |
function hash36($str) { | |
$arr = unpack("C*", pack("L", crc32($str))); | |
return implode(array_map(function($number) { | |
return base_convert($number, 10, 36); | |
}, $arr)); | |
} | |
function self_url() { | |
$path = preg_replace("/\?.*$/", "", $_SERVER['REQUEST_URI']); | |
$protocol = ((!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; | |
return $protocol . $_SERVER['HTTP_HOST'] . $path; | |
} | |
$filename = "db.sqlite"; | |
$init = !file_exists($filename); | |
$db = new PDO('sqlite:' . $filename); | |
//$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
if ($init) { | |
$db->query("CREATE TABLE urls(hash VARCHAR(10), url TEXT)"); | |
} | |
$query = $db->prepare("SELECT * FROM urls WHERE hash = ?"); | |
if (isset($_GET['url'])) { | |
$hash = hash36($_GET['url']); | |
} else { | |
$hash = $_SERVER['QUERY_STRING']; | |
} | |
if (strlen($hash) > 0 && $query->execute(array($hash))) { | |
$result = $query->fetchAll(PDO::FETCH_ASSOC); | |
if (count($result) > 0) { | |
if (isset($_GET['url'])) { | |
echo self_url() . $result[0]['hash']; | |
} else { | |
header('Location: ' . $result[0]['url'], true, 301); | |
} | |
} elseif (isset($_GET['url'])) { | |
$res = $db->prepare("INSERT INTO urls VALUES(?, ?)"); | |
if ($res->execute(array($hash, $_GET['url']))) { | |
echo self_url() . $hash; | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment