Skip to content

Instantly share code, notes, and snippets.

@jasny
Last active December 28, 2015 07:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasny/7468456 to your computer and use it in GitHub Desktop.
Save jasny/7468456 to your computer and use it in GitHub Desktop.
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