← CodePrimer
PHP
Intermediate
Security
Sanitize and validate input
How do I protect against XSS and bad emails?
trim, htmlspecialchars, filter_var.
<?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');
Notes
Validate on input; escape on output.
Keywords: sanitize · validate · xss · htmlspecialchars · filter_var
Related
PHP
Embed PHP inside HTML
How do I mix PHP and HTML?
PHP
PHP comments
How do I write comments in PHP?
PHP
PHP variable rules
What are the rules for PHP variables?
PHP
echo vs print
Should I use echo or print?
PHP
PHP scalar data types
What data types does PHP have?
JavaScript
Live input event
How do I react as the user types?