Last active
December 28, 2015 07:59
-
-
Save jasny/7468456 to your computer and use it in GitHub Desktop.
URL shortener
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 | |
RewriteRule ^(\w{5})$ /index.php?key=$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'); | |
// 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