PHP 8 Intermediate Security · 1 min read

Sanitize and validate input

Start the PHP 8 learning path »

❮ PHP 8 Home All Tutorials ❯

How do I protect against XSS and bad emails?

trim, htmlspecialchars, filter_var.

Example

PHP 8 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.

Need more coins?

You do not have enough coins for this action.

Your balance: 0 coins

Share

Reactions

Loading reactions…