I just developed a URL shortener.
index.php:
<?
$sql_host = "...";
$sql_db = "...";
$sql_user = "...";
$sql_pass = "...";
$conn_error = "Could not connect to database";
$con = mysqli_connect($sql_host, $sql_user, $sql_pass, $sql_db) or die($conn_error);
$hash = htmlspecialchars($_GET["l"]);
$hash = mysqli_real_escape_string($con, $hash);
if (!(empty($hash))) {
$query = "SELECT * FROM `links` WHERE hash = '$hash'";
$row = mysqli_query($con, $query) or die($conn_error);
if (mysqli_num_rows($row)) {
$_ROW = mysqli_fetch_assoc($row);
$url = $_ROW["link"];
header("Location: $url");
exit;
} else {
die("link not available");
}
}
?>
<html>
<head>
<title>gus URL Shortener</title>
</head>
<body>
Type the link to be shortened:<br>
<form action="short.php" method="post">
<input type="text" name="url"><input type="submit" value="Shorten">
</form>
</body>
</html>
The form redirects to short.php where the link is generated:
<html>
<?
$sql_host = "...";
$sql_db = "...";
$sql_user = "...";
$sql_pass = "...";
$conn_error = "Could not connect to database";
$con = mysqli_connect($sql_host, $sql_user, $sql_pass, $sql_db) or die($conn_error);
$url = $_POST["url"];
$url = mysqli_real_escape_string($con, $url);
$hash = hash("crc32", "$url");
if (!(empty($url))) {
if ((substr($url, 0, 7) == "http://") or (substr($url, 0, 8) == "https://")) {
$query = "INSERT INTO `links` (hash, link)
VALUES ('$hash', '$url')";
mysqli_query($con, $query) or die($conn_error);
} else {
die("Your link needs to start with http:// or https://");
}
}
?>
<head>
<title>gus URL Shortener</title>
</head>
<body>
Your Link:
<? echo "<a href='http://gus.netii.net/?l=$hash'>gus.netii.net/?l=$hash</a>";?>
</body>
</html>
Sorry it's not commented but I think it's pretty straightforward. I've been thinking how could I do it so the link doesn't have the "?l=..." like other shorteners have.
UPDATE
Now gus.netii.net is up and running safely, like @CodeX suggested, also without the "?l=" thing after the url to GET with php ! Thanks to all and share it please.