Building a Custom URL Shortener Using PHP and MySQL
URL shorteners are essential tools in today’s web landscape, allowing long, unwieldy URLs to be converted into concise, easy-to-share links. In this tutorial, we’ll explore how to build your own custom URL shortener using PHP, MySQL, and Bootstrap for styling.
Project Overview : URL Shortener
Our URL shortener will:
- Accept a long URL from the user.
- Generate a unique short code.
- Store the long URL and its corresponding short code in the database.
- Redirect users from the short URL to the original long URL.
Follow this video for complete guidance:
Setting Up the Database
Start by creating a database named urlshortner and a table urls:
CREATE TABLE urls ( id INT AUTO_INCREMENT PRIMARY KEY, long_url TEXT NOT NULL, short_code VARCHAR(10) NOT NULL UNIQUE );
Configuration File
The config.php file establishes the database connection and defines the base URL for our shortener:
<?php @session_start(); $con = mysqli_connect('localhost', 'root', '', 'urlshortner'); define("BASE_URL", 'http://localhost/url/'); ?>
User Interface
The index.php file provides a simple, Bootstrap-styled form for users to input long URLs.
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>URL Shortener</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.3/css/bootstrap.min.css" /> </head> <body class="bg-light"> <div class="container mt-5"> <div class="row justify-content-center"> <div class="col-md-6"> <div class="card shadow"> <div class="card-body"> <h3 class="text-center mb-4">URL Shortener</h3> <!-- Display success or error messages --> <?php if (isset($_SESSION['success'])) { ?> <div class="alert alert-success"> <?= $_SESSION['success']; unset($_SESSION['success']); ?> </div> <?php } ?> <?php if (isset($_SESSION['danger'])) { ?> <div class="alert alert-danger"> <?= $_SESSION['danger']; unset($_SESSION['danger']); ?> </div> <?php } ?> <form method="POST" action="shorten.php"> <div class="mb-3"> <label for="long_url" class="form-label">Enter Long URL</label> <input type="url" class="form-control" name="long_url" placeholder="https://example.com" required> </div> <button type="submit" class="btn btn-primary w-100">Shorten URL</button> </form> </div> </div> <p class="text-center mt-3 text-muted">Powered by YourURLShortener</p> </div> </div> </div> </body> </html>
Generating Short URLs
The shorten.php file handles URL validation, short code generation, and database insertion.
<?php include_once('config.php'); function generateShortCode($length = 6) { return substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length); } if ($_SERVER['REQUEST_METHOD'] === 'POST') { $long_url = filter_var($_POST['long_url'], FILTER_SANITIZE_URL); if (filter_var($long_url, FILTER_VALIDATE_URL)) { $short_code = generateShortCode(); $sql = "INSERT INTO urls (long_url, short_code) VALUES ('$long_url', '$short_code')"; if (mysqli_query($con, $sql)) { $_SESSION['success'] = "Shortened URL: <a href='" . BASE_URL . "$short_code'>" . BASE_URL . "$short_code</a>"; } else { $_SESSION['danger'] = "Failed to shorten the URL."; } } else { $_SESSION['danger'] = "Invalid URL provided."; } header('Location: index.php'); } ?>
Redirection Logic
The redirect.php file fetches the long URL from the database and redirects the user.
<?php include_once('config.php'); $short_code = $_GET['code'] ?? ''; $sql = "SELECT long_url FROM urls WHERE short_code = '$short_code'"; $result = mysqli_query($con, $sql); $url = mysqli_fetch_assoc($result); if (isset($url['long_url'])) { header("Location: " . $url['long_url']); exit; } else { echo "URL not found."; } ?>
URL Rewriting with .htaccess
Enable clean URLs by creating an .htaccess file:
RewriteEngine On RewriteRule ^([a-zA-Z0-9]{6})$ redirect.php?code=$1 [L]
Testing the Application
- Navigate to index.php in your browser.
- Enter a long URL and click “Shorten URL.”
- Copy the generated short URL and paste it in your browser. It should redirect to the original long URL.
This URL shortener provides a simple yet powerful solution for managing URLs. You can enhance it further by adding features like analytics, user authentication, or a custom short code input. With a bit of creativity, this can be scaled into a production-grade application!