PHP Intermediate
Live preview
Handle a form safely in PHP
Read, validate and escape form input before showing it back to the visitor.
What you will learn
- Read POST data with a safe default
- Validate an email address
- Escape output with htmlspecialchars()
Never trust what a visitor types. Validate it first, and escape it every time you print it, so nobody can inject HTML or scripts into your page.
The preview shows the page this script produces after a successful submit; the PHP itself runs on a web server, not here.
<?php
$name = trim($_POST['name'] ?? '');
$email = trim($_POST['email'] ?? '');
$errors = [];
if ($name === '') {
$errors[] = 'Please enter your name.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Please enter a valid email address.';
}
if (!$errors) {
// htmlspecialchars() turns < > & " into safe text before printing
$safeName = htmlspecialchars($name, ENT_QUOTES, 'UTF-8');
echo "<h1>Thank you, {$safeName}!</h1>";
echo '<p>We will reply to you by email.</p>';
} else {
foreach ($errors as $error) {
echo '<p class="error">' . htmlspecialchars($error) . '</p>';
}
}
This preview is an HTML demonstration of the expected result, prepared by the instructor. The PHP code was not run.
Run the preview when you are readyIt runs in an isolated sandbox with no access to this site or your account.