Skip to content

Instantly share code, notes, and snippets.

@jasny
Last active Dec 28, 2015
Embed
What would you like to do?
URL shortener
RewriteEngine On
RewriteRule ^(\w{5})$ /index.php?key=$1
<?php
header('Content-Type: text/plain');
// Add url
if (isset($_GET['add'])) {
$db = dba_open("/tmp/shortener.db", "c", "db4");
if (!$db) trigger_error("dba_open failed", E_USER_ERROR);
$key = substr(base_convert(md5($_GET['add']), 10, 36), 0, 5);
dba_insert($key, $_GET['add'], $db);
dba_close($db);
echo "http://{$_SERVER['HTTP_HOST']}/$key";
exit();
}
// Get url
$db = dba_open("/tmp/shortener.db", "r", "db4");
if (!$db) trigger_error("dba_open failed", E_USER_ERROR);
if (isset($_GET['key']) && dba_exists($_GET['key'], $db)) {
$url = dba_fetch($_GET['key'], $db);
}
dba_close($db);
if (!isset($url)) {
header("HTTP/1.0 404 Not Found");
echo "Not found $_GET[key]";
exit();
}
header("Location: $url");
echo $url;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment