Parameters, Request Body, Form Data and JSON

3.Parameters, Request Body, Form Data and JSON

M

In this chapter

We'll learn the four places a request carries data — query parameters, path parameters, form bodies and JSON bodies — how PHP turns each into something you can use, how URL encoding works, how form fields become arrays, why every value arrives as a string, and how to validate and convert input before trusting it.

16–18 min

The Problem in Real Life

Mia builds three things at once: the free-slots page, slots.php?date=2026-11-07; the booking form, which also lets customers tick extra services; and, for the mobile app a partner is building, an endpoint that receives a booking as JSON.

The form's ticked services arrive as only one value. The JSON endpoint finds $_POST completely empty. And $_GET['date'] happily contains "tomorrow", which crashes the date code three functions later.

M

The data is in the request somewhere. Why does PHP put each kind in a different place?

Mia

Guessing Where Data Is vs. Knowing Each Channel

Query and path

?date=… lands in $_GET; /bookings/4811 needs to be read from the URL itself.

Form vs. JSON bodies

PHP decodes form bodies into $_POST — JSON stays raw in php://input.

Strings from strangers

Every value is text typed by someone else. Validate and convert before use.

Parameters, Request Body, Form Data and JSON

Four channels for data: a request can carry information in the URL and in its body, in several formats. PHP handles each one differently. This chapter covers:

  • Query parameters: ?date=2026-11-07 and URL encoding.
  • Path parameters: /bookings/4811.
  • Form data: URL-encoded and multipart bodies, and arrays.
  • JSON bodies: reading php://input.
  • Everything is a string: validating and converting input.

Query parameters: everything after ? in a URL is the query string: name=value pairs joined by &, like ?date=2026-11-07&barber=ben. PHP decodes it into $_GET before your script starts — for any method, even a POST to book.php?source=email. Because URLs may only contain certain characters, other characters are URL-encoded: a space becomes + or %20, : becomes %3A, and é becomes %C3%A9. Build query strings with http_build_query($params), which encodes everything correctly, and read them with $_GET or parse_str(), which decode it.

Building and reading query strings
<?php
$query = http_build_query(['date' => '2026-11-07', 'time' => '16:00', 'customer' => 'Clare Lefèvre']);
echo "/slots.php?{$query}\n";
parse_str($query, $params); // what PHP does to fill $_GET
print_r($params);
echo urlencode('16:00 & beard'), "\n"; // + for spaces (forms)
echo rawurlencode('16:00 & beard'), "\n"; // %20 for spaces (paths)
// /slots.php?date=2026-11-07&time=16%3A00&customer=Clare+Lef%C3%A8vre
// Array ( [date] => 2026-11-07 [time] => 16:00 [customer] => Clare Lefèvre )
// 16%3A00+%26+beard
// 16%3A00%20%26%20beard

Path parameters: modern URLs often put the identifier in the path: /bookings/4811 instead of booking.php?id=4811. PHP doesn't decode these for you: the full path is in $_SERVER['REQUEST_URI'], and the part after the script name in $_SERVER['PATH_INFO']. Your code — or a framework's router — matches it with a pattern like #^/bookings/(\d+)$# and takes the id from the match. With one front script, public/index.php, and the web server sending every request to it, every URL in the application can be a clean path; that's how Laravel works.

Matching a path parameter
<?php
foreach (['/bookings/4811', '/bookings/abc', '/slots'] as $path) {
if (preg_match('#^/bookings/(\d+)$#', $path, $match)) {
$id = (int) $match[1];
echo "{$path} → booking {$id}\n";
} else {
echo "{$path} → no booking route\n";
}
}
// /bookings/4811 → booking 4811
// /bookings/abc → no booking route
// /slots → no booking route

Form data: a normal form sends its fields in the body, encoded like a query string, with the header Content-Type: application/x-www-form-urlencoded. PHP decodes it into $_POST. Forms that upload files use multipart/form-data (Act 15), and PHP fills both $_POST and $_FILES. To send several values for one name — ticked services — end the field's name with brackets: name="services[]". PHP then builds an array, ['cut', 'beard']; without the brackets only the last value survives, today's bug. name="customer[phone]" builds a nested array the same way.

JSON bodies: apps and JavaScript code usually send JSON with Content-Type: application/json. PHP does not decode JSON into $_POST — it stays empty, the second bug. Read the raw body from the php://input stream (Act 15) and decode it: json_decode(file_get_contents('php://input'), true, flags: JSON_THROW_ON_ERROR). Answer broken JSON with 400 Bad Request. The table below shows where each kind of data ends up, and the example shows real output for all three.

Table — Request data in PHP
DataExamplePHP gives youNote
Query string?date=2026-11-07$_GET['date']For every method
Path/bookings/4811$_SERVER['REQUEST_URI'] / PATH_INFOMatch it yourself or with a router
Form bodycustomer=Sam+Cole$_POST['customer']Content-Type: application/x-www-form-urlencoded
Form with filesmultipart/form-data$_POST and $_FILESAct 15
JSON body{"customer": "Sam Cole"}file_get_contents('php://input')$_POST stays empty

Where PHP puts request data

POST /api.php/bookings/4811?source=app

one request, several channels

split

?source=app

→ $_GET['source']

/bookings/4811

→ PATH_INFO: match it yourself

Body

depends on Content-Type

body by Content-Type

application/x-www-form-urlencoded

→ $_POST

multipart/form-data

→ $_POST + $_FILES

application/json

→ php://input only

Real output: the same script, three kinds of request
$ curl "http://localhost:8000/misc.php?what=request&date=2026-11-07&barber=ben"
GET /misc.php?what=request&date=2026-11-07&barber=ben
$_GET: {"what":"request","date":"2026-11-07","barber":"ben"}
$_POST: []
$ curl -d "customer=Sam Cole&services[]=cut&services[]=beard" "http://localhost:8000/misc.php?what=request"
POST /misc.php?what=request
CONTENT_TYPE: application/x-www-form-urlencoded
$_GET: {"what":"request"}
$_POST: {"customer":"Sam Cole","services":["cut","beard"]}
$ curl -H "Content-Type: application/json" -d '{"customer":"Sam Cole"}' "http://localhost:8000/misc.php?what=request"
POST /misc.php?what=request
CONTENT_TYPE: application/json
$_POST: []
php://input: {"customer":"Sam Cole"}

Everything is a string: whatever the channel, input arrives as strings (or arrays of strings) — "4811", never the integer 4811, and never trustworthy. A field may be missing, empty, an array where you expected text, or "tomorrow" where you expected a date. So read input with defaults ($_GET['date'] ?? ''), validate it (a pattern, a range, a list of allowed values, DateTimeImmutable::createFromFormat()), convert it to the right type, and only then pass it deeper into the code — so that functions inside work with real ints and dates (Act 14's TypeError lesson). filter_var($value, FILTER_VALIDATE_INT) validates and converts in one step, returning false for bad input. Act 17 builds full form validation on this.

Validating and converting at the edge
<?php
declare(strict_types=1);
function readSlotQuery(array $query): array
{
$date = DateTimeImmutable::createFromFormat('!Y-m-d', $query['date'] ?? '');
if ($date === false || $date->format('Y-m-d') !== ($query['date'] ?? '')) {
return ['error' => 'date must look like 2026-11-07'];
}
$barberId = filter_var($query['barber'] ?? '', FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
return ['date' => $date, 'barberId' => $barberId === false ? null : $barberId];
}
foreach ([['date' => '2026-11-07', 'barber' => '12'], ['date' => 'tomorrow'], ['date' => '2026-02-30', 'barber' => 'x']] as $query) {
$result = readSlotQuery($query);
echo isset($result['error'])
? "rejected: {$result['error']}\n"
: "ok: {$result['date']->format('D j M')}, barber " . var_export($result['barberId'], true) . "\n";
}
// ok: Sat 7 Nov, barber 12
// rejected: date must look like 2026-11-07
// rejected: date must look like 2026-11-07

Key Takeaway

Requests carry data in four places: the query string (?date=…, decoded into $_GET for any method; URL-encoded, so build with http_build_query()), the path (/bookings/4811, matched from REQUEST_URI or PATH_INFO by a router), form bodies (urlencoded or multipart, decoded into $_POST and $_FILES; name="services[]" makes an array), and JSON bodies, which PHP leaves in php://input for you to json_decode with JSON_THROW_ON_ERROR ($_POST stays empty). Every value arrives as a string from a stranger: read with defaults, validate, convert to real types (filter_var, createFromFormat) at the edge, then pass typed values inward.

Why This Matters

Reading input is where web code meets the outside world, and where most security problems begin. Knowing exactly which channel carries what, and converting it once at the edge, keeps the rest of the code clean and typed.

Frameworks wrap all four channels in one request object — Laravel's $request->input('date') reads the query, form or JSON body alike — but they're built on exactly these mechanisms.

Services arrive as an array, the JSON endpoint reads php://input, and "tomorrow" is rejected at the door. Meanwhile Mia has used $_GET, $_POST, $_SERVER and $_FILES without ever declaring them — and a colleague's code uses $_REQUEST and reads $_SERVER['HTTP_X_FORWARDED_FOR'] as the customer's IP address. What are these variables, and which of them can be trusted? That's the next chapter: PHP superglobals.