Added additional error handling with hash collision

This commit is contained in:
mischa 2022-08-24 15:19:25 +00:00
parent 0466bd0720
commit 595667d433
1 changed files with 11 additions and 11 deletions

View File

@ -30,7 +30,6 @@ function count_urls($dbh) {
}
function generate_short($url, $dbh) {
if(!preg_match("/^((https?|ftp)[:\/\/].*\/{2,})/i",$url)) {
return false;
}
@ -42,34 +41,33 @@ function generate_short($url, $dbh) {
} 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 {
$charset = str_shuffle(CHARSET);
$hash = substr($charset, 0, HASH_LENGTH);
$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) {
$hash = substr($charset, 0, HASH_LENGTH);
if ($loop == 10) {
$hash = "ERROR<br />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()) {
print "FAILURE INSERTING\n";
$hash = "ERROR<br />Failed to insert hash!";
}
}
return $hash;
@ -184,6 +182,8 @@ body {
<?php
if ($link === false) {
echo "<span style='color: red;'>Unknown / Invalid URL</span>";
} elseif (str_contains($link, "ERROR")) {
echo "<span style='color: red;'>$link</span>";
} else {
if ($link != '') {
echo "<span style='color: white;'>" . BASE_URL . $link . "</span>";