×

php · level 3 · unit 6 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A reads the request and picks the code that answers it.

Every visit to a web app arrives as a request: a method such as GET or POST, plus a path such as /pets. Frameworks keep a list of routes, each linking a method and a path to a , a closure that builds the answer.

The router's job is small. It reads $_SERVER["REQUEST_METHOD"] and $_SERVER["REQUEST_URI"], looks up the matching and calls its handler. No match? It answers 404, the web's code for not found. Here, the top three lines pretend the request.

<?php
$_SERVER["REQUEST_METHOD"] = "GET";
$_SERVER["REQUEST_URI"] = "/pets";
$routes = [
    "GET /" => fn() => "Welcome to the pet shop!",
    "GET /pets" => fn() => "Rex, Tom and Bella",
    "POST /pets" => fn() => "Pet added",
];
$key = $_SERVER["REQUEST_METHOD"] . " " . $_SERVER["REQUEST_URI"];
$handler = $routes[$key] ?? fn() => "404 Not Found";
echo $handler() . "\n";

Real frameworks add patterns like /pets/{id}, but underneath they do exactly this lookup.