← CodePrimer
PHP Intermediate Security

Sanitize and validate input

How do I protect against XSS and bad emails?

trim, htmlspecialchars, filter_var.

Sample
<?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

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share