#Its unique return True; } } if ($_POST) { #We have been posted stuff if ($_POST['url'] and $_POST['id']) { #We have been posted a url. Yay if ($_POST['slug']) { #We have been posted a slug too so just pop these into the db $sql = "UPDATE `url_shortener` SET \t`url`='" . $_POST['url'] . "', `slug`='" . $_POST['slug'] . "' WHERE `id`=" . $_POST['id'] . ";"; $result = $conn->query($sql); } else { #No slug so generate one. $slug = substr(md5(microtime()), rand(0, 26), 5); while (!checkSlug($conn, $slug)) { #While there is a duplicate slug in the db, go and generate a new one. $slug = substr(md5(microtime()), rand(0, 26), 5); } #Now we have a unique slug $sql = "UPDATE `url_shortener` SET `url`='" . $_POST['url'] . "', `slug`='" . $slug . "' WHERE `id`=" . $_POST['id'] . ";"; $result = $conn->query($sql); $_SESSION['message'] = 'Successfully added.'; } header("Location: list.php"); } } if (!$_GET) { #No get variable passed header('Location: list.php'); }
function checkSlug($slug, $options) { if ($slug != '*' && ($q = $options['db']->query("\n\t\t\t\t\t\t\tSELECT " . $options['col_name'] . "\n\t\t\t\t\t\t\tFROM " . $options['table'] . "\n\t\t\t\t\t\t\tWHERE id != '" . $options['id'] . "'\n\t\t\t\t\t\t\t\tAND " . $options['col_name'] . " = '" . $slug . "'" . $options['where'] . "\n\t\t\t\t\t\t"))) { if (is_numeric($i = substr($slug, strrpos($slug, '_') + 1))) { $slug = substr($slug, 0, strrpos($slug, '_') + 1) . ($i + 1); } else { $slug .= '_1'; } return checkSlug($slug, $options); } else { return $slug; } }
#We have been posted data $error = False; if (!$_POST['slug']) { # We haven't been sent a slug so generate one $slug = substr(md5(microtime()), rand(0, 26), 5); # Check whether the slug is already in the db while (!checkSlug($conn, $slug)) { # Lets loop until we get a unique one $slug = substr(md5(microtime()), rand(0, 26), 5); #$sql = "SELECT `id` FROM `url_shortener` WHERE `slug` = '" . $slug . "';"; #$result = $conn->query($sql); } } else { # We have been sent a slug so save it into the $slug variable $slug = $_POST['slug']; if (!checkSlug($conn, $slug)) { #Its a duplicate slug. print 'Duplicate slug listed in database. Please remove it or try again.'; $error = True; } } #Now we have a unique slug so we can add the info to the db if (!$error) { $sql = "INSERT INTO `url_shortener` (`slug`, `url`) VALUES ('" . $slug . "', '" . $_POST['url'] . "')"; $result = $conn->query($sql); #print('Added redirect: ' . $slug . ' -> ' . $_POST['url'] ); $_SESSION['messages'][] = 'Added redirect: ' . $slug . ' -> ' . $_POST['url']; header('Location: list.php'); } } include '../header.php';