Commit Diff


commit - 0466bd072079fa46015e919aec41b1678be27a56
commit + 595667d433cd049b144e49eea8c986906f300737
blob - eeb368d815f460b3d1465423c5a58384cb3e88a1
blob + c4237d8348b02557ece82afd708cd409ed91ee40
--- index.php
+++ index.php
@@ -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>";