PHP 8
Intermediate
Security
· 1 min read
Sanitize and validate input
How do I protect against XSS and bad emails?
trim, htmlspecialchars, filter_var.
Example
<?php
$email = trim((string) ($_POST['email'] ?? ''));
$message = trim((string) ($_POST['message'] ?? ''));
if (! filter_var($email, FILTER_VALIDATE_EMAIL)) {
exit('Invalid email');
}
echo htmlspecialchars($message, ENT_QUOTES, 'UTF-8');
Line-by-Line Walkthrough
Validate on input; escape on output.