Forms, $_POST and validation
How a PHP page receives form data, checks it and shows errors without losing what the user typed.
Most PHP screening tasks are a form: show it, receive it, validate it, save it. The whole flow fits on one page if you keep the steps in order.
Receiving
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
The null-coalescing operator ?? avoids notices when a field is missing. Always trim; a trailing space is the usual reason a valid email fails validation.
Validating
$errors = [];
if ($name === '') {
$errors['name'] = 'Enter your name';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['email'] = 'Enter a valid email address';
}
Collect errors in an array keyed by field, then show each next to its input. Never validate with regular expressions you wrote in a hurry when a filter exists.
Showing it back safely
<input name="name" value="<?= htmlspecialchars($name) ?>">
Anything that came from the user and goes back into HTML passes through htmlspecialchars. That one habit prevents cross-site scripting.
Saving
$stmt = $pdo->prepare('INSERT INTO leads (name, email) VALUES (:name, :email)');
$stmt->execute(['name' => $name, 'email' => $email]);
Prepared statements keep SQL and data apart. Concatenating $email into the query string is the error interviewers look for first.
The PHP test asks about $_POST, htmlspecialchars, prepared statements and isset. All four come from this one flow.
More in Programming