Just for inspiration: My version of an URL-Shortener (kind of older code previously featured on my blog):
require_once('database.class.php');
$db = new database('localhost', '', '', '');
$pass = '123';
$base_url = 'http://go.nico.is/';
function is_url($url) {
if(!preg_match("#^http(s)?://[a-z0-9-_.]+\.[a-z]{2,4}#i", $url)) {
return false;
} else {
return true;
}
}
function url_encrypt($id) {
$codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$base = strlen($codeset);
$converted = "";
while ($id > 0) {
$converted = substr($codeset, ($id % $base), 1) . $converted;
$id = floor($id/$base);
}
return $converted;
}
function url_decrypt($converted) {
$codeset = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$base = strlen($codeset);
$c = 0;
for ($i = strlen($converted); $i; $i--) {
$c += strpos($codeset, substr($converted, (-1 * ( $i - strlen($converted) )),1))
* pow($base,$i-1);
}
return $c;
}
if($_GET['do'] != '' && isset($_GET['url']) && $_GET['pass'] == $pass) {
$url = rawurldecode($_GET['url']);
if($_GET['do'] == 'remove') {
if($db->delete('urls', '`url`=\''.$url.'\'')) {
$note = 'true';
} else {
$note = 'false';
}
} elseif($_GET['do'] == 'stats') {
$note = (($db->get_element('urls', 'stats', '`url`=\''.$url.'\'')) ? $db->get_element('urls', 'stats', '`url`=\''.$url.'\'') : '0');
} elseif($_GET['do'] == 'add') {
if(!$db->get_element('urls', 'converted', '`url`=\''.$url.'\'')) {
$id = $db->get_next_id('urls');
if($db->insert('urls', array('id' => $id, 'url' => $url, 'converted' => $converted, 'stats' => 0))) {
$note = $base_url.url_encrypt($id);
} else {
$note = 'false';
}
} else {
$note = $base_url.$db->get_element('urls', 'converted', '`url`=\''.$url.'\'');
}
}
} elseif(isset($_GET['converted'])) {
$id = url_decrypt($_GET['converted']);
$url = $db->get_element('urls', 'url', '`id`=\''.$id.'\'');
$db->update('urls', array('stats' => ((int)$db->get_element('urls', 'stats', '`id`=\''.$id.'\'') + 1)), '`id`=\''.$id.'\'');
header('HTTP/1.1 301 Moved Permanently');
header('Location: '.$url);
exit;
}
if($note != '') {
echo $note;
}