PHP URL Shortener App

Learn PHP in 10 Minutes
Learn PHP in 10 Minutes

Live stream set for 2025-12-17 at 14:00:00 Eastern

Ask questions in the live chat about any programming or lifestyle topic.

This livestream will be on YouTube or you can watch below.

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 (affiliate) links. I may earn a commission if you purchase through them - at no extra cost to you.

About Edward

Edward is a software engineer, web developer, and author dedicated to helping people achieve their personal and professional goals through actionable advice and real-world tools.

As the author of impactful books including Learning JavaScript, Learning Python, Learning PHP, Mastering Blender Python API, and fiction The Algorithmic Serpent, Edward writes with a focus on personal growth, entrepreneurship, and practical success strategies. His work is designed to guide, motivate, and empower.

In addition to writing, Edward offers professional "full-stack development," "database design," "1-on-1 tutoring," "consulting sessions,", tailored to help you take the next step. Whether you are launching a business, developing a brand, or leveling up your mindset, Edward will be there to support you.

Edward also offers online courses designed to deepen your learning and accelerate your progress. Explore the programming on languages like JavaScript, Python and PHP to find the perfect fit for your journey.

📚 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.
🎓 Ready to Learn? – Check out his Online Courses to turn your ideas into results.

Leave a Reply

Your email address will not be published. Required fields are marked *