← Back to PHP Course | Chapter 10: Forms & Validation | Lesson 3 of 8

PHP Form Sanitization

Sanitizing Emails

Sanitization cleans or transforms input into a safe, expected form — stripping unwanted characters or encoding special ones — while validation only checks whether input is acceptable; the two work together, not interchangeably.

Example: Sanitizing Emails

php
<?php
$email = "  [email protected]  ";
$sanitized = trim($email);
echo "[" . $sanitized . "]";
// Sanitizing cleans input; validating separately checks it's acceptable
?>

Sanitizing Strings

filter_var($value, FILTER_SANITIZE_STRING) and related filters strip or encode potentially dangerous characters from user input, though many of PHP's sanitize filters are deprecated in PHP 8.1+ in favor of explicit encoding at output time.

Example: Sanitizing Strings

php
<?php
$comment = "<b>Hello</b> World";
echo htmlspecialchars($comment);
// Many old filter_var sanitize filters are deprecated in PHP 8.1+
?>

Sanitizing Numbers

trim() removes stray leading/trailing whitespace that users often introduce accidentally by copy-pasting, which can otherwise cause an exact-match comparison (like a coupon code check) to fail unexpectedly.

Example: Sanitizing Numbers

php
<?php
$coupon = "  SAVE10  ";
echo "[" . trim($coupon) . "]";
?>

Stripping Whitespace

Sanitizing input doesn't replace parameterized queries for database safety — sanitization reduces risk, but prepared statements are what actually prevent SQL injection, and both should be used together, not one instead of the other.

Example: Stripping Whitespace

php
<?php
$username = trim(" alice ");
// Sanitizing reduces risk, but prepared statements prevent SQL injection
echo $username;
?>

Removing HTML Tags

The safest general rule is to sanitize input on the way in for storage, and separately encode output (with htmlspecialchars()) on the way out to HTML, since the correct escaping depends on where the data is being used.

Example: Removing HTML Tags

php
<?php
$input = "<script>alert('x')</script>Hello";
$forStorage = strip_tags($input);
$forDisplay = htmlspecialchars($forStorage);
echo $forDisplay;
?>
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.