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
- Review the code and required PHP extensions.
- Configure database and storage settings outside the public web root where applicable.
- Add authorization, rate limiting and logging for public-facing endpoints.
- 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.