PHP URL Shortener App

Learn PHP in 10 Minutes
On 2 min, 53 sec read

Build a Simple URL Shortener Using PHP and MariaDB

In this tutorial, we will build a simple URL shortener using PHP and MariaDB. The application will allow users to generate short URLs, view a list of previously created URLs, and serve redirects when the short URLs are accessed. We will use HTML5 and the Fetch API for a modern, interactive interface.

Step 1: Database Setup

Create a MariaDB table to store original and short URLs.

CREATE TABLE urls (
    id INT AUTO_INCREMENT PRIMARY KEY,
    original_url VARCHAR(2083) NOT NULL,
    short_code VARCHAR(10) NOT NULL UNIQUE,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

Step 2: HTML Form for Shortening URLs

<form id="urlForm">
  <input type="url" id="originalUrl" placeholder="Enter URL" required>
  <button type="submit">Generate Short URL</button>
</form>

<ul id="urlList">
  <!-- Short URLs will be listed here -->
</ul>

Step 3: JavaScript with Fetch API

document.getElementById('urlForm').addEventListener('submit', async (e) => {
    e.preventDefault();
    const originalUrl = document.getElementById('originalUrl').value;

    const response = await fetch('shorten.php', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({url: originalUrl})
    });

    const data = await response.json();
    if (data.shortUrl) {
        const li = document.createElement('li');
        li.innerHTML = `<a href="${data.shortUrl}" target="_blank">${data.shortUrl}</a>`;
        document.getElementById('urlList').appendChild(li);
    }
});

Step 4: PHP Backend for Shortening and Redirects

File: shorten.php

// shorten.php
header('Content-Type: application/json');
$data = json_decode(file_get_contents('php://input'), true);

$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');

function generateShortCode($length = 6) {
    return substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length);
}

$originalUrl = filter_var($data['url'], FILTER_SANITIZE_URL);
$shortCode = generateShortCode();

$stmt = $pdo->prepare('INSERT INTO urls (original_url, short_code) VALUES (?, ?)');
$stmt->execute([$originalUrl, $shortCode]);

$shortUrl = 'https://yourdomain.com/r.php?c=' . $shortCode;

echo json_encode(['shortUrl' => $shortUrl]);

File: r.php

// r.php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$code = $_GET['c'];

$stmt = $pdo->prepare('SELECT original_url FROM urls WHERE short_code = ?');
$stmt->execute([$code]);
$url = $stmt->fetchColumn();

if ($url) {
    header('Location: ' . $url);
    exit;
} else {
    echo 'URL not found';
}

Step 5: Running the Application

  • Place the PHP files on your server.
  • Ensure your MariaDB database is configured correctly.
  • Open the HTML form in a browser, enter a URL, and generate a short link.
  • Click the short URL to test the redirect.

Screenshots And Screencast

URL Shortener HTML Code
Gnome Text Editor Displaying URL Shortener HTML Code

URL Shortener PHP Save Code
Gnome Text Editor Displaying URL Shortener PHP Save Code

URL Shortener PHP Redirect Code
Gnome Text Editor Displaying URL Shortener PHP Redirect Code

URL Shortener SQL Code
Gnome Text Editor Displaying URL Shortener SQL Code

Add URL Shortener
Web Browser Displaying Adding URL Shortener

PHPMyAdmin Table URL Shortener
Web Browser Displaying PHPMyAdmin Database Table URL Shortener

PHP Basic URL Shortener Video

Learning Resources

Book: Learning PHP
https://www.amazon.com/Learning-PHP-Programming-Edward-Ojambo-ebook/dp/B0D442PR8T

Course: Learning PHP
https://ojamboshop.com/product/learning-php

One-on-One Programming Tutorials & PHP App Services:
https://ojambo.com/contact

🚀 Recommended Resources


Disclosure: Some of the links above are referral links. I may earn a commission if you make a purchase at no extra cost to you.

About Edward

Edward is a software engineer, author, and designer dedicated to providing the actionable blueprints and real-world tools needed to navigate a shifting economic landscape.

With a provocative focus on the evolution of technology—boldly declaring that “programming is dead”—Edward’s latest work, The Recession Business Blueprint, serves as a strategic guide for modern entrepreneurship. His bibliography also includes Mastering Blender Python API and The Algorithmic Serpent.

Beyond the page, Edward produces open-source tool review videos and provides practical resources for the “build it yourself” movement.

📚 Explore His Books – Visit the Book Shop to grab your copies today.

💼 Need Support? – Learn more about Services and the ways to benefit from his expertise.

🔨 Build it Yourself – Download Free Plans for Backyard Structures, Small Living, and Woodworking.