Asia/Kolkata
Projects

URL Shortener: Modern & Scalable Web App

URL Shortener: Modern & Scalable Web App – project image by Supratim Mondal
March 25, 2025
Sharing long, complex URLs filled with tracking parameters is messy. This project is a lightweight, self-hosted URL shortener built with PHP and MySQL. It converts long URLs into short, unique codes and redirects users when they visit the short link. The project was designed to learn raw PHP routing, database schema design, Apache rewriting rules, and hash collision handling. The database is built on MySQL with a single index-optimized table: By indexing the short_code column, database lookups remain fast even as the table grows to thousands of entries. When a user submits a URL without specifying a custom alias:
  • The app takes the MD5 hash of the original URL.
  • It encodes the hash into a Base62 string (using characters a-z, A-Z, and 0-9).
  • It takes the first 6 characters of the Base62 string as the short code.
  • Collision Check: The app queries the database to check if that short code is already in use. If a collision is detected (which is rare for a 6-character Base62 space), the app appends a random salt to the URL and re-hashes until a unique code is generated.
To support clean links (e.g. http://short.local/abcde instead of http://short.local/index.php?code=abcde), the project uses an Apache .htaccess file to rewrite incoming requests: This configuration intercepts requests, verifies that they do not point to an actual file or directory, and redirects the code segment to redirect.php in the background.
  • Backend Language: PHP 7.4+
  • Database: MySQL / MariaDB
  • Web Server: Apache (with mod_rewrite enabled)
  • Frontend: HTML5, CSS3 (minimal, responsive layout)
  • Preventing Loops: Users could theoretically input the short link of the app itself, creating an infinite redirect loop. I resolved this by adding input validation that matches the domain name of the submitted URL against the host header of the server, rejecting any attempts to shorten URLs containing the app's own domain name.
  • SQL Injection: To prevent SQL injection attacks through custom codes, the database queries use PDO prepared statements with parameter binding instead of string concatenation.