CREATE TABLE IF NOT EXISTS `counter`
(
`id` INT(10) UNSIGNED NOT NULL
)
ENGINE=myisam;

INSERT INTO `counter` (`id`) VALUES (0);

CREATE TABLE IF NOT EXISTS `id_to_url`
(
`id` INT(10) UNSIGNED NOT NULL,
`url` TEXT NOT NULL,
UNIQUE KEY `id` (`id`)
) ENGINE=myisam;

/*!50100 PARTITION BY KEY (id) PARTITIONS 64 */;
CREATE TABLE IF NOT EXISTS `urls_to_hash`
(
`hash` BINARY(16) NOT NULL,
`id` INT(10) UNSIGNED NOT NULL,
UNIQUE KEY `hash` (`hash`)
)
ENGINE=myisam;
/*!50100 PARTITION BY KEY (`hash`) PARTITIONS 64 */;







= 0; $t--) {
$a = floor($num / pow(BASE,$t));
$out = $out.substr(INDEX,$a,1);
$num = $num-($a*pow(BASE,$t));
}
return $out;
}
// Convert a base 73 number to a base 10 number
function dec73to10($dec73) {
GLOBAL $rindex;
$len = strlen($dec73);
$out = $rindex[$dec73[$len-1]];
$k = 1;
for($j = $len-2;$j >= 0;$j--)
{
if(!isset($rindex[$dec73[$j]]))
{
header('HTTP/1.1 400 Bad Request');
die('The requested URI does not conform to this URL shortener\'s syntax');
}
$out = bcadd($out,bcmul($rindex[$dec73[$j]],bcpow(73,$k)),0);
$k++;
}
return $out;
}

if(strlen($_SERVER['REQUEST_URI']) > 1) // Request for a shortened URL
{
dbconnect();
if(!$longurl = mysql_fetch_array(mysql_query('SELECT url FROM id_to_url WHERE id = '.dec73to10(substr($_SERVER['REQUEST_URI'],1))),MYSQL_ASSOC))
{
header('HTTP/1.1 404 Not Found');
die('The shortened URL you have requested does not exist in our database');
}
header('Location: '.$longurl['url']);
exit(0);
}
elseif(isset($_POST['url']) && trim($_POST['url'])) // Request to add a URL to the database (or check if it exists), return short version for display
{
dbconnect();
($_POST['url'] = stripslashes($_POST['url'])) && $md5 = md5($_POST['url'],TRUE);
if(@!$p = parse_url($_POST['url']) || !isset($p['host']) || preg_match("'.?3hr.in$'",$p['host']))
echo 'Sorry, the URL you requested to shorten was not valid.';
else
{
mysql_query('LOCK TABLES urls_to_hash');
mysql_query('INSERT IGNORE urls_to_hash (hash,id) SELECT ''.mysql_real_escape_string($md5).'',id+1 FROM counter') or die(mysql_error());
if(mysql_affected_rows())
{
mysql_query('INSERT IGNORE id_to_url (id,url) SELECT id+1,''.mysql_real_escape_string($_POST['url']).'' FROM counter') or die(mysql_error());
mysql_query('UPDATE counter SET id = id + 1') or die(mysql_error());
}
mysql_query('UNLOCK TABLES urls_to_hash');
$shorturl = dec10to73(array_shift(mysql_fetch_array(mysql_query('SELECT id FROM urls_to_hash WHERE hash = ''.mysql_real_escape_string($md5).'''),MYSQL_ASSOC))); // Fetch numerical ID of URL and convert it from base 10 to 72
echo 'Your shortened URL: http://3hr.in/'.$shorturl.'';
}
}
?>
URL: