Build Your Own URL Shortener

Build Your Own URL Shortener

Building a URL shortener is a classic project that many software developers tackle, mainly because it starts as a simple API but can quickly become complex when you need to scale it. In fact, designing a URL shortener is a common interview question since it challenges developers to think about functionality and scalability.

How URL Shortening Works

  1. Take a long URL as input.
  2. Generate a short, unique key for the URL.
  3. Store the original URL and key in a database.
  4. When users visit the short URL, redirect them to the original URL.

Here is a Javascript Example

const express = require('express');
const app = express();
const port = 3000;

app.use(express.json()); // Middleware to parse JSON requests

// In-memory database to store URLs for demonstration purposes
const urlDatabase = {};

// Function to generate a short code
function generateShortCode() {
return Math.random().toString(36).substr(2, 6); // Generates a 6-character code
}

// Endpoint to shorten a URL
app.post('/shorten', (req, res) => {
const originalUrl = req.body.url;

// Generate a unique short code
let shortCode = generateShortCode();

// Ensure unique code by regenerating if it already exists
while (urlDatabase[shortCode]) {
shortCode = generateShortCode();
}

// Store the original URL with the short code
urlDatabase[shortCode] = originalUrl;

// Send back the shortened URL
res.json({ shortUrl: `http://localhost:${port}/${shortCode}` });
});

// Endpoint to redirect from the short URL to the original URL
app.get('/:shortCode', (req, res) => {
const shortCode = req.params.shortCode;

// Look up the short code in the database
const originalUrl = urlDatabase[shortCode];

if (originalUrl) {
// Redirect to the original URL
res.redirect(originalUrl);
} else {
// Send an error if the short code is not found
res.status(404).json({ error: "URL not found" });
}
});

// Start the server
app.listen(port, () => {
console.log(`URL shortener service listening at http://localhost:${port}`);
});

Here is a PHP Example

<?php
// Connect to SQLite database
$db = new PDO('sqlite:url_shortener.db');

// Function to generate a unique short code
function generateShortCode($length = 6) {
return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
}

// Function to shorten a URL
function shortenURL($originalUrl) {
global $db;

// Generate a unique short code
do {
$shortCode = generateShortCode();
$stmt = $db->prepare("SELECT COUNT(*) FROM urls WHERE short_code = ?");
$stmt->execute([$shortCode]);
$exists = $stmt->fetchColumn() > 0;
} while ($exists);

// Insert the original URL and short code into the database
$stmt = $db->prepare("INSERT INTO urls (original_url, short_code) VALUES (?, ?)");
$stmt->execute([$originalUrl, $shortCode]);

// Return the full shortened URL
return "http://localhost/shortener.php?code=$shortCode";
}

// Function to redirect to the original URL
function redirectToOriginalURL($shortCode) {
global $db;

// Look up the original URL by short code
$stmt = $db->prepare("SELECT original_url FROM urls WHERE short_code = ?");
$stmt->execute([$shortCode]);
$originalUrl = $stmt->fetchColumn();

if ($originalUrl) {
// Redirect to the original URL
header("Location: $originalUrl");
exit();
} else {
// Return an error if the short code is not found
echo "Error: URL not found.";
}
}

// Main Logic
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// Handle shortening a URL
$originalUrl = $_POST['url'];
if (filter_var($originalUrl, FILTER_VALIDATE_URL)) {
$shortUrl = shortenURL($originalUrl);
echo "Shortened URL: <a href='$shortUrl'>$shortUrl</a>";
} else {
echo "Invalid URL provided.";
}
} elseif (isset($_GET['code'])) {
// Handle redirecting based on short code
$shortCode = $_GET['code'];
redirectToOriginalURL($shortCode);
} else {
// Display a form to shorten a URL
echo '<form method="POST">
<label for="url">Enter URL to shorten:</label>
<input type="text" name="url" id="url" required>
<button type="submit">Shorten URL</button>
</form>';
}
?>

Why Choose T.LY Instead?

While building your URL shortener can be fun and educational for most businesses and users, T.LY is a practical, cost-effective, and reliable choice. It handles all the complex aspects of URL management, leaving you to focus on growing your audience and sharing content without technical hassle.


Author Tim Leland

Tim Leland

Tim Leland brings over 20 years of software development experience to the table, creating products used by millions around the globe. In 2019, he founded T.LY with a vision to build the world’s shortest URL shortener—and since then, the platform’s popularity has soared. Under Tim’s leadership, T.LY has evolved into a top-tier solution recognized for its reliability and ease of use, now serving millions of satisfied users worldwide.

Ready to improve how you manage links?

T.LY URL Shortener makes long links look cleaner and easier to share! Add your own Custom Domains to personalize your brand. Create Smart Links to customize a URL's destination. Generate QR codes to promote your business.

Sign Up for Free
About T.LY
T.LY is the best link management service to track, brand, and share short URLs and QR codes. Install our free Browser Extension with over 450,000 users from the extension store to automatically shorten links in one easy click! We support Chrome, Firefox, Edge and Opera.