Database & Utilities

PHP MySQL URL Shortener Starter

PDO URL shortener foundation using random codes and HTTP/HTTPS URL validation.

Overview

PDO URL shortener foundation using random codes and HTTP/HTTPS URL validation.

What this script does

This starter demonstrates the core implementation pattern. Adapt database fields, configuration and error handling to your application.

Source code

<?php
declare(strict_types=1);
function createShortCode(PDO $pdo,string $url): string {
    if (!filter_var($url,FILTER_VALIDATE_URL) || !in_array(strtolower((string)parse_url($url,PHP_URL_SCHEME)),['http','https'],true)) {
        throw new InvalidArgumentException('Only valid HTTP(S) URLs are accepted.');
    }
    for ($i=0;$i<5;$i++) {
        $code=rtrim(strtr(base64_encode(random_bytes(6)),'+/','-_'),'=');
        try {
            $s=$pdo->prepare('INSERT INTO short_urls(code,target_url,created_at) VALUES(:code,:url,NOW())');
            $s->execute(['code'=>$code,'url'=>$url]); return $code;
        } catch (PDOException $e) { if ($e->getCode()!=='23000') throw $e; }
    }
    throw new RuntimeException('Could not create unique code.');
}

Download starter source: Download PHP MySQL URL Shortener Starter source

Installation and customization

  1. Review the code and required PHP extensions.
  2. Configure database and storage settings outside the public web root where applicable.
  3. Add authorization, rate limiting and logging for public-facing endpoints.
  4. Test valid, invalid and boundary inputs before deployment.

> This is a learning starter, not a complete production application. Apply the security and deployment requirements of your project.