Skip to main content

One Branch per Route

Routing decides which code answers which request. PHP has no built-in route table — the router script reads the request itself: $_SERVER["REQUEST_URI"] holds the path, and exploding it on / gives the segments.

A segment that is data — the 7 in /users/7 — is a path parameter: instead of matching it literally, the router captures it and hands it to the handler. Frameworks add conveniences on top, but this is the mechanism underneath.


Routes and Path Values

Two routes: the list at /users and one user at /users/{id}. The second segment of the path is the path parameter — the piece of the URL that is data.

A route with a path parameter

The same router script sends /users to one branch and /users/7 to another, and the second path segment hands over the 7 as data.

Prompt
Write a PHP script whose router script explodes the request path into segments and handles two routes: GET /users returning a list line and GET /users/{id} answering about one user with the id from the second segment. Serve it with the built-in server, request both routes and print the responses.
Output: PHP script

Query Parameters

The part after ? holds query parameters — options for the request, like a search text or a limit: /search?q=php&limit=2. PHP parses them for you into the $_GET array, always as strings, with ?? supplying a default for missing ones.

The rule of thumb: the path says which resource, the query says how — filters, sorting, paging.

Reading the query string

The handler reads q and limit from $_GET. The second request skips limit, so the handler falls back to a default — missing parameters are normal, plan for them.

Prompt
Write a PHP script with a /search handler that reads the q and limit query parameters from $_GET, using ?? to fall back to a default limit when it is missing. Serve it with the built-in server, request it once with both parameters and once with only q, printing the responses.
Output: PHP script