query("SELECT COUNT(*) FROM ". DB_TABLE);
return $sth->fetchColumn();
}
function generate_short($url, $dbh) {
if(!preg_match("/^((https?|ftp)[:\/\/].*\/{2,})/i",$url)) {
return false;
}
if (substr($url, 0, strlen(BASE_URL)) == BASE_URL){
return false;
}
if (!empty($_SERVER['HTTP_X_CLIENTIP'])) {
$clientip = $_SERVER['HTTP_X_CLIENTIP'];
} else {
$clientip = $_SERVER['REMOTE_ADDR'];
}
$sth = $dbh->prepare("SELECT id FROM " . DB_TABLE . " WHERE url=?");
$sth->bindParam(1, $url, PDO::PARAM_STR);
$sth->execute();
if ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$hash = $row['id'];
} else {
$hash = substr(str_shuffle(CHARSET), 0, HASH_LENGTH);
$sth = $dbh->prepare("SELECT COUNT(*) FROM " . DB_TABLE . " WHERE id=?");
$sth->bindParam(1, $hash, PDO::PARAM_STR, HASH_LENGTH);
$sth->execute();
$loop = 0;
while ($sth->fetchColumn() > 0) {
if ($loop == 10) {
$hash = "ERROR
Unable to create hash!";
break;
}
$hash = substr(str_shuffle(CHARSET), 0, HASH_LENGTH);
$sth->bindParam(1, $hash, PDO::PARAM_STR, HASH_LENGTH);
$sth->execute();
$loop++;
}
$sth = $dbh->prepare("INSERT INTO " . DB_TABLE . " (id, url, ip, count) VALUES (?, ?, ?, '0')");
$sth->bindParam(1, $hash, PDO::PARAM_STR, HASH_LENGTH);
$sth->bindParam(2, $url, PDO::PARAM_STR);
$sth->bindParam(3, $clientip, PDO::PARAM_STR, 255);
if (!$sth->execute()) {
$hash = "ERROR
Failed to insert hash!";
}
}
return $hash;
}
function find_short($hash, $dbh) {
$sth = $dbh->prepare("SELECT * FROM " . DB_TABLE . " WHERE id=?");
$sth->bindParam(1, $hash, PDO::PARAM_STR, HASH_LENGTH);
$sth->execute();
if ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$link = $row['url'];
$sth = $dbh->prepare("UPDATE " . DB_TABLE . " SET count = count + 1 WHERE id=?");
$sth->bindParam(1, $row['id'], PDO::PARAM_STR, HASH_LENGTH);
$sth->execute();
} else {
$link = false;
}
return $link;
}
if (isset($_POST['url'])) {
if ($_POST['url'] != '' && strlen($_POST['url']) > 0) {
$db = db_connect();
$link = generate_short($_POST['url'], $db);
} else {
$link = false;
}
}
if (isset($_GET['hash']) && $_GET['hash'] != '' && strlen($_GET['hash']) > 0) {
$path = explode('/', $_SERVER['REQUEST_URI']);
$uri = $path[count($path)-1];
if ($uri != '') {
$db = db_connect();
$link = find_short($uri, $db);
if ($link != '') {
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Wed, 29 Feb 1984 00:00:00 GMT");
header("Location: $link", TRUE, 301);
}
}
}
if ($callback == 'NO') {
$db = db_connect();
$count = count_urls($db);
?>
Currently holding entries.