Make Your Own URL Shortener Using PHP or Python

 

Make Your Own URL Shortener Using PHP or Python


Introduction

The internet is full of long, complicated URLs. Whether it’s a product link from Amazon, a YouTube video, or a long Google search query, these URLs can be messy to share.

That’s why URL shorteners like Bit.ly, TinyURL, and Rebrandly became so popular. They transform long links into short, easy-to-share URLs. For example:

Original: https://www.amazon.com/dp/B07FZ8S74R/ref=cm_sw_em_r_mt_dp_example Shortened: https://bit.ly/abc123

In this guide, we’ll walk through how to make your own URL shortener using PHP or Python, step by step. By the end, you’ll have your very own tool that works just like Bit.ly—completely under your control.




Why Build Your Own URL Shortener?

You might be wondering: why not just use Bit.ly or TinyURL? Here are some great reasons:

  • Full Control – No dependency on third-party services.

  • Customization – You can brand your short links (e.g., mybrand.link/offer).

  • No Limits – Free services often restrict the number of URLs.

  • Analytics – You can track clicks and user behavior your way.

  • Great Learning Project – Teaches you about databases, HTTP requests, and web development.


Core Features of a URL Shortener

Before coding, let’s define what our shortener will do:

  1. Take a long URL (like https://example.com/article/1234).

  2. Generate a short code (e.g., abcd12).

  3. Save mapping in a database (short code → long URL).

  4. Redirect users who visit the short code.

  5. (Optional) Add analytics (clicks, timestamps, devices).


Step 1: Decide on Language (PHP vs Python)

Both PHP and Python are excellent for this project.

  • PHP: Works great with traditional hosting. Easy to deploy on shared hosting or cPanel.

  • Python: Best if you’re comfortable with frameworks like Flask or Django. Easier for adding advanced features later.

We’ll cover both approaches.


Step 2: Setting Up the Database

We need to store URLs and their shortened versions. A simple MySQL table works:

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

This table stores each long URL, its short code, and the time it was created.


Step 3: PHP Version

Let’s build a simple PHP-based shortener.

PHP Directory Setup

/url-shortener ├── index.php ├── redirect.php ├── db.php

Database Connection (db.php)

<?php $host = "localhost"; $user = "root"; $pass = ""; $dbname = "shortener"; $conn = new mysqli($host, $user, $pass, $dbname); if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } ?>

Main File (index.php)

This file lets users input long URLs.

<?php include("db.php"); ?> <!DOCTYPE html> <html> <head> <title>URL Shortener</title> </head> <body> <h1>PHP URL Shortener</h1> <form method="post"> <input type="text" name="long_url" placeholder="Enter URL" required> <button type="submit">Shorten</button> </form> <?php if (isset($_POST['long_url'])) { $long_url = $_POST['long_url']; $short_code = substr(md5($long_url . time()), 0, 6); $sql = "INSERT INTO urls (long_url, short_code) VALUES ('$long_url', '$short_code')"; $conn->query($sql); echo "Short URL: <a href='redirect.php?c=$short_code'>http://localhost/redirect.php?c=$short_code</a>"; } ?> </body> </html>

Redirect File (redirect.php)

<?php include("db.php"); if (isset($_GET['c'])) { $code = $_GET['c']; $sql = "SELECT long_url FROM urls WHERE short_code='$code'"; $result = $conn->query($sql); if ($result->num_rows > 0) { $row = $result->fetch_assoc(); header("Location: " . $row['long_url']); exit(); } else { echo "Invalid URL"; } } ?>

✅ With this, you have a working PHP-based URL shortener.


Step 4: Python Version (Flask)

Now, let’s build the same with Python + Flask.

Install Flask

Flask App (app.py)

from flask import Flask, request, redirect, render_template import mysql.connector import hashlib import time app = Flask(__name__) db = mysql.connector.connect( host="localhost", user="root", password="", database="shortener" ) cursor = db.cursor() @app.route("/", methods=["GET", "POST"]) def home(): if request.method == "POST": long_url = request.form["long_url"] short_code = hashlib.md5((long_url + str(time.time())).encode()).hexdigest()[:6] cursor.execute("INSERT INTO urls (long_url, short_code) VALUES (%s, %s)", (long_url, short_code)) db.commit() return f"Short URL: <a href='/{short_code}'>http://localhost:5000/{short_code}</a>" return ''' <form method="post"> <input type="text" name="long_url" placeholder="Enter URL" required> <button type="submit">Shorten</button> </form> ''' @app.route("/<code>") def redirect_to_long(code): cursor.execute("SELECT long_url FROM urls WHERE short_code=%s", (code,)) result = cursor.fetchone() if result: return redirect(result[0]) return "Invalid URL" if __name__ == "__main__": app.run(debug=True)

✅ This will create a working Python-based URL shortener on http://localhost:5000.


Step 5: Adding Features

Once you have the basics, you can extend your shortener with:

  1. Analytics Dashboard

    • Track number of clicks per link.

    • Store IP address, device, or referrer.

  2. Custom Short Codes

    • Let users pick their own short code (e.g., mysite.com/sale).

  3. Expiry Links

    • Allow links to expire after X days or clicks.

  4. API Support

    • Add an API so other apps can use your shortener.


Step 6: Deploying Your URL Shortener

Once you’re ready, deploy:

  • PHP App: Deploy on shared hosting or VPS with Apache/Nginx.

  • Python App: Use services like Heroku, Railway, or AWS.

If you own a domain, point it to your hosting server—so your short links look like https://yourdomain.com/abc123.


Real-World Example

When I built my first URL shortener, I hosted it on a small VPS. I used it to create branded short links for my freelance portfolio. Clients loved it because:

  • Links looked clean.

  • I could track clicks.

  • No ads or third-party branding.

It even became a mini side project for others in my network who wanted short links.


FAQs

Q1: Which is better—PHP or Python for URL shortener?

  • PHP is easier if you have shared hosting.

  • Python is better if you want to scale or add advanced features.

Q2: Do I need a database?
Yes, unless you want a static, one-time shortener. A database allows unlimited mappings.

Q3: Can I make money from a URL shortener?
Yes, some services show ads during redirects. But for personal/brand use, focus on clean, ad-free links.

Q4: How secure are shortened URLs?
You should validate inputs to avoid malicious links. Adding reCAPTCHA can prevent spam.

Q5: Can I make it public so anyone can shorten links?
Yes, but then you’ll need moderation and spam prevention features.


Conclusion

Building your own URL shortener with PHP or Python is not only fun but also practical. You’ll learn:

  • How to handle databases.

  • How to use redirects.

  • How to build real-world web apps.

The best part? You’ll own your own shortener—no limits, no ads, and full control.

So, whether you use PHP for simplicity or Python for scalability, your custom shortener is just a few steps away.

Start today, and soon you’ll be creating links as clean as Bit.ly—only branded your way!

Post a Comment

0 Comments