How to Build Your Own URL Shortener with PHP & MySQL

Please wait 0 seconds...
Scroll Down and click on Go to Link for destination
Congrats! Link is Generated

 

How to Build Your Own URL Shortener with PHP & MySQL 🚀🔗

Creating your own URL shortener gives you full control over your links, branding, and analytics. In this guide, we’ll cover:

Setting up PHP & MySQL for URL shortening
Creating the database and tables
Building the PHP script for shortening and redirecting URLs
Adding an admin panel for managing short links


1. Why Build Your Own URL Shortener?

No third-party limits – You own your data
Custom branding – Use your domain (e.g., sho.rt/xyz)
Click tracking – Monitor performance
More security – Avoid spam filters from public shorteners


2. Setting Up Your Development Environment

🛠️ Requirements

  • PHP (7.x or later)
  • MySQL Database
  • Apache/Nginx Server (XAMPP/LAMP recommended)

📌 For local development: Install XAMPP (Download Here)


3. Creating the MySQL Database

Step 1: Create a Database

Run this SQL query in phpMyAdmin or MySQL CLI:

CREATE DATABASE url_shortener;

Step 2: Create a Table for Shortened URLs

USE url_shortener;

CREATE TABLE links (
    id INT AUTO_INCREMENT PRIMARY KEY,
    short_code VARCHAR(10) UNIQUE NOT NULL,
    long_url TEXT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

4. Creating the PHP Shortening Script

📂 Project Structure:

/url_shortener
  ├── index.php  (Shortener form)
  ├── shorten.php  (Processes URL)
  ├── redirect.php  (Handles redirection)
  ├── db.php  (Database connection)

🔹 Step 1: Database Connection (db.php)

<?php
$host = "localhost";
$user = "root"; // Change for live servers
$pass = ""; // Change for live servers
$db = "url_shortener";

$conn = new mysqli($host, $user, $pass, $db);

if ($conn->connect_error) {
    die("Database connection failed: " . $conn->connect_error);
}
?>

🔹 Step 2: URL Shortener Form (index.php)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>URL Shortener</title>
</head>
<body>
    <h2>Shorten Your URL</h2>
    <form action="shorten.php" method="POST">
        <input type="url" name="long_url" required placeholder="Enter a long URL">
        <button type="submit">Shorten</button>
    </form>
</body>
</html>

🔹 Step 3: Shortening Logic (shorten.php)

<?php
require 'db.php';

if (isset($_POST['long_url'])) {
    $long_url = trim($_POST['long_url']);
    
    // Generate a unique short code
    $short_code = substr(md5(time()), 0, 6);
    
    // Insert into database
    $stmt = $conn->prepare("INSERT INTO links (short_code, long_url) VALUES (?, ?)");
    $stmt->bind_param("ss", $short_code, $long_url);
    $stmt->execute();
    
    echo "Shortened URL: <a href='redirect.php?c=$short_code' target='_blank'>sho.rt/$short_code</a>";
}
?>

🔹 Step 4: Redirection Script (redirect.php)

<?php
require 'db.php';

if (isset($_GET['c'])) {
    $short_code = $_GET['c'];

    // Fetch original URL
    $stmt = $conn->prepare("SELECT long_url FROM links WHERE short_code = ?");
    $stmt->bind_param("s", $short_code);
    $stmt->execute();
    $stmt->bind_result($long_url);
    $stmt->fetch();
    
    if ($long_url) {
        header("Location: " . $long_url);
        exit;
    } else {
        echo "URL not found!";
    }
}
?>

5. Creating an Admin Panel for Managing URLs

📂 Additional Files:

/admin
  ├── index.php  (Dashboard)
  ├── delete.php  (Delete URL)

🔹 Step 1: Admin Dashboard (admin/index.php)

<?php
require '../db.php';

$result = $conn->query("SELECT * FROM links ORDER BY created_at DESC");
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Admin Panel</title>
</head>
<body>
    <h2>URL Management</h2>
    <table border="1">
        <tr>
            <th>ID</th>
            <th>Short Code</th>
            <th>Long URL</th>
            <th>Created</th>
            <th>Action</th>
        </tr>
        <?php while ($row = $result->fetch_assoc()) { ?>
            <tr>
                <td><?= $row['id'] ?></td>
                <td><a href="../redirect.php?c=<?= $row['short_code'] ?>" target="_blank"><?= $row['short_code'] ?></a></td>
                <td><?= $row['long_url'] ?></td>
                <td><?= $row['created_at'] ?></td>
                <td><a href="delete.php?id=<?= $row['id'] ?>">Delete</a></td>
            </tr>
        <?php } ?>
    </table>
</body>
</html>

🔹 Step 2: Delete Shortened URLs (admin/delete.php)

<?php
require '../db.php';

if (isset($_GET['id'])) {
    $id = $_GET['id'];
    $stmt = $conn->prepare("DELETE FROM links WHERE id = ?");
    $stmt->bind_param("i", $id);
    $stmt->execute();
}

header("Location: index.php");
?>

6. Enhancements & Features to Add

Custom short codes – Allow users to choose their code
Click tracking – Store clicks in the database
User authentication – Secure admin panel
QR Code Generation – Auto-generate QR codes for each short URL


7. Deploying Your URL Shortener

📌 Hosting Options

Shared Hosting (cPanel) – Easy & affordable
VPS (DigitalOcean, Linode, AWS, etc.) – For full control
Self-Hosted (Local Server) – For private use

Steps:
1️⃣ Upload files via FTP or File Manager
2️⃣ Import the SQL database
3️⃣ Update db.php with live server credentials
4️⃣ Set up domain (sho.rt) using .htaccess for clean URLs


8. Conclusion

🎯 Congratulations! You’ve successfully built your own URL shortener with PHP & MySQL!

🚀 Features you implemented:
✅ Shortening & redirecting URLs
✅ Admin panel for managing links
✅ Secure database storage

🔗 Next Steps:
💡 Add analytics for tracking clicks
💡 Use custom domains for branding
💡 Implement an API for programmatic URL shortening

👉 Want more features? Let me know in the comments! 😊

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.