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
- Take a long URL as input.
- Generate a short, unique key for the URL.
- Store the original URL and key in a database.
- 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.
Related Posts
Tim Leland
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