We have all seen and used those URL shorting sites. It takes a very long link and converts it to a short link for emailing. When you click the short link it takes you to the link website address.
Below I thought I would make my own. Feel free to use the below to make your own and have fun.
SQL Table
CREATE TABLE links (
id int(11) NOT NULL AUTO_INCREMENT,
link_text varchar(255) NOT NULL,
url varchar(255) NOT NULL,
PRIMARY KEY (id)
);
PHP Code
<?php
// Database connection settings
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$dbname = "links";
// Retrieve the Link term from the query string
$link_text = $_GET['link'];
// Create a database connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check for errors in the connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Build the SQL query to retrieve the URL link for the link text
$sql = "SELECT url FROM links WHERE link_text = '$link_text'";
// Execute the query and retrieve the result
$result = $conn->query($sql);
// Check for errors in the query
if ($result === false) {
die("Query failed: " . $conn->error);
}
// Check if there is a result for the search term
if ($result->num_rows > 0) {
// Retrieve the URL link from the result
$row = $result->fetch_assoc();
$url = $row['url'];
// Redirect the user to the URL link
header("Location: $url");
exit;
} else {
// If there is no result for the search term, display an error message
echo "No results found for '$link_text'";
}
// Close the database connection
$conn->close();
?>
.htaccess file
RewriteEngine On
RewriteRule ^lookup/([^/]+)/?$ shortlink.php?link=$1 [L,QSA]