Skip to content
Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

Youths Forum Youths Forum Youths Forum

Tech Blogs & Programming Tutorials

  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones

Categories

  • Automobiles (12)
    • Cars (7)
  • Blog (103)
    • Poems (2)
    • Space (2)
  • Command (2)
  • Education (2)
  • Entertainment (4)
  • Gadgets (9)
    • Phones (8)
      • Android Phones (4)
  • HTML Templates (11)
  • IT Training Institutes (1)
  • Lifestyle (4)
  • News (51)
  • Others (23)
  • Programming (296)
    • API (16)
    • CSS (83)
    • Database (4)
    • Hosting (1)
    • HTML (37)
    • JavaScript (117)
      • JQuery (27)
      • ReactJS (7)
    • PHP (116)
  • Python (3)
  • recipes (1)
  • SEE Result (1)
  • Server (3)
  • Blog
  • News
  • Programming
    • PHP
    • JavaScript
    • JQuery
    • CSS
    • HTML
    • API
  • Stock Market Live
  • Automobiles
    • Cars
  • Gadgets
    • Phones
    • Android Phones
Close

Search

PHP

Building a Custom URL Shortener Using PHP and MySQL

By Admin
December 4, 2024 3 Min Read
0

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:

https://www.youtube.com/watch?v=oX_Pc67S8Ow

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!

Author

Admin

Follow Me
Other Articles
Previous

Post Tweet to Twitter Using PHP

Next

Design a Digital Clock with Alarm Using jQuery

No Comment! Be the first one.

Leave a Reply

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

FIFA World Cup 2026 Predict and Win by SportsGuff

Recent Posts

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide
  • Chiranjibi Adhikari Appointed Acting President of CAN Federation
  • How to Design a Student Marksheet Using HTML and CSS

Tags

adsense ai animate animation animation using HTML and CSS API blog calculator chatgpt Cryptocurrency CSS css animation design Email Facebook featured filemanager file manager free template google htaccess HTML image Instagram interview javascript JQuery jquery ui NADA AutoShow NADA Auto Show 2024 password PHP Progressive Web App PWA QR random react reactjs Rotate travel Twitter vpn youthforum youthsforum youtube

About Us

At Youths Forum, we are passionate about sharing knowledge that empowers students, educators, professionals, and technology enthusiasts.

Our Mission

Our mission is simple: to make technology and education accessible, understandable, and beneficial for everyone. We strive to create content that helps our readers learn new skills and stay updated with industry developments.

RSS RSS

  • Unpacking Nepal’s Record Rs 2.12 Trillion Budget and What It Means for You Admin
  • How to Write a Strong Scholarship Application: The Ultimate Step-by-Step Guide Admin
  • How to Prepare for Exams Without Stress: The Ultimate Science-Backed Guide Admin

Quick Links

  • Stock Market Live
  • Parliament Election 2082
Copyright 2026 — Youths Forum. All rights reserved. Blogsy WordPress Theme