bhylu.com

Advertisements

PHP HTTP Requests and Responses

An HTTP request has a method and target as well as optional headers and a body. A response also has a status and headers; its text alone does not describe the whole exchange.

How it works

PHP exposes request metadata through server-provided variables in a web SAPI. A normal CLI execution has no incoming browser request, so this first example builds an explicit fixture instead. GET generally retrieves a representation; a state-changing operation needs an appropriate method and additional protections. Method selection does not supply authentication or CSRF defence by itself.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l http-model.php
php http-model.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · http-model.php

<?php
declare(strict_types=1);

$request = ["method"=>"GET", "path"=>"/loans", "query"=>["page"=>"2"]];
$page = filter_var($request["query"]["page"], FILTER_VALIDATE_INT, ["options"=>["min_range"=>1]]);
echo $request["method"], " ", $request["path"], "\n";
echo "Requested page: ", $page, "\n";

Expected result

GET /loans
Requested page: 2

The method and path remain separate from the parsed page value. A real handler would choose a status for invalid input and encode the response according to its content type. The fixture lets you trace the parsing contract before depending on a web server or a particular rewrite configuration.

Check the official PHP manual for detailed version and API contracts.