Skip to content

Phils Blog and Stuff

TELECOMS. VIRTUALIZATION. IT. CODING. and more…

Menu
  • Home
  • Resources
    • Subnet Mask Cheat Sheet
    • Easy Dmarc+Email
    • MX Tool Box
    • LOAD BALANCING & SRE
  • SHOP
  • SOLUTIONS
  • SERVICES
  • Contact Me
Menu

A simple link shortener.. Fun little project…

Posted on 14/03/202313/03/2023 by Phil

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]

POSTS

  • Home Assistant. Add water meter with PHP+MQTT+YML.
  • Automating your home with Home Assistant. Initial install and config (Hyper-V).
  • The importance of setting up email security correctly.
  • Automate Debian installations with Seed, DHCP and Nginx.
  • A simple link shortener.. Fun little project…

WORD CLOUD

3CX 3CX Phone System Apache Asterisk Cacti CentOS CRM DHCP DNS Email Fail over Failover File System Firewall FreeBSD FreeNAS FXO IAX install IP IP PBX Linux M0n0wall Nottingham Open Source PBX PFSense PHP Router Server SIP snom SSH TrixBox ubuntu VLAN Voice VoIP VPN vyatta WAN Website WiFi yealink ZFS

© 2025 Phils Blog and Stuff | Powered by Superbs Personal Blog theme