Skip to main content

The Server Runs Your Script

PHP turns web serving inside out compared to most languages: you do not write a server that runs forever — the web server runs your script, once per request. The script is the handler: superglobals like $_SERVER and $_GET hold the request, and header() plus echo build the response.

PHP ships its own web server for development: php -S host:port router.php answers every request by running that one script. The examples here really run it: each one writes its handler script to a temporary file, starts php -S on a free port as a child process, sends real HTTP requests to it, prints the answers, and stops the server — so every example runs and finishes by itself.


A First Handler

The smallest possible handler script writes a line of text. Everything an API does — JSON, status codes, routing — happens inside this same request-in, echo-out shape.

Hello from a handler

The handler script echoes one line; the client reads exactly that as the response body, with status 200 OK filled in automatically.

Prompt
Write a PHP script with the smallest handler script that echoes a hello line. Serve it with PHP's built-in web server on a free port, send one GET request and print the response status and body, then stop the server.
Output: PHP script

Answering with JSON

An API handler does three things: set the Content-Type header, choose a status code, and encode the data — header() first, then echo json_encode($value).

Order matters: headers must be sent before the first byte of the body.

A JSON endpoint

The handler encodes an array straight into the response. The client receives valid JSON and the right content type — this is the skeleton of every endpoint in the rest of this group.

Prompt
Write a PHP script whose handler answers with a JSON-encoded user array, setting the Content-Type header with header() before echoing. Serve it with the built-in server, request it and print the status, content type and JSON body.
Output: PHP script