How to get form data
Short answer
The data of a post form is in the $_POST array under the field names. A field may be missing, so supply a default:
<?php
$name = trim($_POST['name'] ?? '');
echo $name === '' ? 'empty' : $name;From the address
The parameters after the question mark go into $_GET:
<?php
$page = filter_var($_GET['page'] ?? 1, FILTER_VALIDATE_INT) ?: 1;
echo $page;Validation
Check every field and collect the errors in an array:
<?php
$input = ['name' => '', 'email' => 'anna@example'];
$errors = [];
if (trim($input['name']) === '') {
$errors['name'] = 'Name is required';
}
if (filter_var($input['email'], FILTER_VALIDATE_EMAIL) === false) {
$errors['email'] = 'Invalid email';
}
echo json_encode($errors);Output:
{"name":"Name is required","email":"Invalid email"}Functions used in this recipe
- trim — Removes whitespace and other characters from both ends of a string.
- filter_var — Validates or sanitises a value by a given rule.
- htmlspecialchars — Replaces HTML special characters with safe entities.