Skip to content
Tutorials Center
My learning

Topics

Lesson 135 of 147 ยท Projects

Project: URL Shortener

Build a URL shortener in PHP in four stages - validate and normalize links, generate unique codes, store them with PDO and SQLite, then route requests and redirect.

A URL shortener turns a long address such as https://example.com/articles/2026/05/a-very-long-title?utm_source=newsletter into something like https://sho.rt/k3Fq9xA. When someone visits the short link, the server looks the code up and sends the browser to the original address. It is a classic project because it is small, yet it exercises exactly the skills a PHP web developer needs: validating untrusted input, generating unique identifiers, storing data with PDO, routing by path and sending redirects with the right status code.

You will build the shortener in four stages. Each stage is a complete program you can run and change. Because the editor has no web server, requests are simulated as plain arrays (a method, a path and form data) and each handler returns the response a real server would send. The last section shows how the same code runs on a real server.

Before you start, it helps to know PDO, prepared statements, routing and HTTP headers and redirects.

The plan

flowchart TD
  A["POST /shorten<br/>url=https://..."] --> B{"Valid http or https URL?"}
  B -->|"no"| C["422 error"]
  B -->|"yes"| D{"Already stored?"}
  D -->|"yes"| E["Return existing code"]
  D -->|"no"| F["Generate unique code<br/>and INSERT"]
  F --> G["201 with short link"]
  H["GET /k3Fq9xA"] --> I{"Code found?"}
  I -->|"no"| J["404"]
  I -->|"yes"| K["Count a hit<br/>302 Location: original URL"]

Creating a link validates, deduplicates and stores; visiting a link looks the code up and redirects.

The finished app has three jobs: create short links, redirect visitors and count clicks. The structure:

Piece Responsibility
normalizeUrl() Accept only well-formed http(s) addresses
LinkRepository All SQL: create, find by code, count hits
Shortener::handle() Routing and responses (status codes, headers)

Stage 1: validating the URL

A shortener is a favorite target for abuse, so the first rule is: never store or redirect to something you did not check. A link like javascript:alert(1) would run code in the visitor's browser, and a file:///etc/passwd link is useless at best. Accept only absolute http and https URLs with a plausible host.

Codes can come from a counter, too. Encoding the row ID in base 62 (digits, lowercase and uppercase letters) gives short strings: ID 125 becomes 21, and a million links still fit in four characters. The demo below includes both ideas:

PHP Stage 1: URL validation and base-62 codes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Sequential codes are compact but guessable: anyone can walk through 1, 2, 3, โ€ฆ and discover every link. For public shorteners, random codes are better, and that is what stage 2 uses. (Base 62 is still useful: you could encode a random 40-bit number instead of a counter.)

https://localhost/admin is rejected only because the host has no dot. Real services also block private addresses (127.0.0.1, 192.168.x.x) so the shortener cannot be used to probe internal networks, and they check links against lists of phishing sites.

Now the data layer. One table is enough: code is UNIQUE (it is the lookup key), url is UNIQUE too, so shortening the same address twice returns the same code, and hits counts visits.

Random codes can in rare cases collide, so the repository retries when the database reports a unique-constraint violation, instead of checking first and inserting second (which has a race condition when two requests run at once). The code generator is passed in as a function, which also lets the demo use a predictable sequence:

PHP Stage 2: the link repository

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Notice that every query uses a prepared statement; the URL comes from users and must never be glued into SQL. Also see that hits = hits + 1 is done inside SQL. Reading the number, adding 1 in PHP and writing it back would lose clicks when two visitors arrive at the same time.

Stage 3: routing and redirects

The application class ties validation, storage and HTTP together. It receives the method, path and form data, and returns a response array. Three routes:

  • GET / shows a form (in a real app).
  • POST /shorten creates a link, answering 201 Created (or 200 for an existing one) with a JSON body.
  • GET /{code} redirects with 302 Found and a Location header, or answers 404.
  • GET /stats/{code} reports the number of hits.

Why 302 and not 301? A 301 (permanent) redirect is cached by browsers, so after the first visit they skip your server and you can no longer count clicks or change the target. A 302 (temporary) or 307 keeps every visit flowing through you. Choose 301 only when you do not care about analytics and the link will never change.

PHP Stage 3: the complete shortener

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Read the output from top to bottom. The first POST creates the link (201), the identical second POST returns the same code (200), the bad URL is refused (422), two visits are redirected (302) and counted, the stats route reports 2 hits, and unknown codes and unsupported methods give 404.

A few design points worth noting:

  • The code pattern is strict ([0-9A-Za-z_-]{3,12}), so odd paths never reach the database.
  • Route order matters. /stats/abc also looks like a path with a slash, so the stats route is checked before the catch-all code route; and the code pattern has no slash, so it cannot match /stats/abc anyway.
  • Error responses are JSON here because the endpoints are API-style. A public site would render an HTML 404 page for browser visits.

Stage 4: running it for real

On a real server the simulated array becomes the actual request. This front controller connects the stage 3 classes to PHP's superglobals (load them with Composer's autoloader; see autoloading and Composer):

PHP
<?php
// public/index.php
declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';

$pdo = new PDO('sqlite:' . __DIR__ . '/../storage/links.db', options: [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);

$generate = fn (): string => rtrim(strtr(base64_encode(random_bytes(6)), '+/', '-_'), '=');
$app = new Shortener(new LinkRepository($pdo, $generate), 'https://sho.rt');

$path = rawurldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) ?: '/');
$response = $app->handle($_SERVER['REQUEST_METHOD'], $path, $_POST);

http_response_code($response['status']);
foreach ($response['headers'] as $name => $value) {
    header("$name: $value");
}
if ($response['body'] !== []) {
    echo json_encode($response['body'], JSON_UNESCAPED_SLASHES);
}

Start it locally with php -S localhost:8000 -t public public/index.php; the last argument makes the built-in server send every request through the front controller. In nginx you would use try_files $uri /index.php?$query_string;. Keep storage/ outside the web root, and in production create the table once with a migration instead of in the constructor.

Before you put a shortener on the public internet, think about abuse:

  1. Rate limit creation per IP address, or require an account.
  2. CSRF protection for the HTML form (CSRF); a pure JSON API uses tokens or same-site cookies instead.
  3. Block your own domain as a target to prevent redirect loops, and block known malicious domains.
  4. Escape any URL you show in HTML with htmlspecialchars() (XSS and output escaping).
  5. Log redirects asynchronously if traffic grows; one UPDATE per click is fine for thousands of visits per day but not for millions.

Ideas for extending the project

  • Let users choose a custom alias (validate it with the same code pattern and reserve words like stats and shorten).
  • Add expiry dates and a deleted_at column.
  • Record the referrer and day of each click in a second table and show a chart.
  • Generate a QR code for each short link.
  • Add an HTML front end with AJAX so the form shows the new short link without reloading.
  • Move the SQL into an ORM-style model and write tests with an in-memory database (Testing).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the shortener accept only http and https URLs?

    Redirecting to arbitrary schemes is a security risk, so only absolute http(s) URLs with a sensible host are accepted.
  2. 2. Why does the repository retry on a unique-constraint error instead of checking whether the code exists first?

    Check-then-insert has a race condition. Letting the UNIQUE constraint decide and retrying on failure is atomic.
  3. 3. What is the practical difference between a 301 and a 302 redirect for a shortener?

    A permanent redirect may be cached by the browser. A temporary one sends every visit through you, which keeps analytics and lets you change the target.
  4. 4. Why is the click counter updated with SET hits = hits + 1 in SQL?

    Reading, incrementing in PHP and writing back lets concurrent requests overwrite each other's updates.
  5. 5. What is a drawback of using sequential IDs encoded in base 62 as public codes?

    Counters are compact but predictable. Random codes make it infeasible to discover links by guessing.

Summary

  • Validate every submitted URL: absolute, http or https, a plausible host and no embedded credentials.
  • Use random, URL-safe codes (or base-62 encoded numbers) and let a UNIQUE constraint plus a retry loop guarantee uniqueness.
  • Keep SQL in a repository class with prepared statements, and count hits with an atomic hits = hits + 1.
  • Route by method and path with strict patterns; answer 201/200 for creation, 302 plus Location for redirects, 404 for unknown codes and 422 for bad input.
  • Prefer 302 when you want analytics; a 301 is cached by browsers.
  • Think about abuse (rate limits, blocked targets, escaping, CSRF) before going public.

Next: PHP Cheat Sheet