PHP Form Sanitization
In this page:
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
$email = " [email protected] ";
$sanitized = trim($email);
echo "[" . $sanitized . "]";
// Sanitizing cleans input; validating separately checks it's acceptable
?>
Login to try C/C++/Java/PHP code in the editor
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
$comment = "<b>Hello</b> World";
echo htmlspecialchars($comment);
// Many old filter_var sanitize filters are deprecated in PHP 8.1+
?>
Login to try C/C++/Java/PHP code in the editor
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
$coupon = " SAVE10 ";
echo "[" . trim($coupon) . "]";
?>
Login to try C/C++/Java/PHP code in the editor
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
$username = trim(" alice ");
// Sanitizing reduces risk, but prepared statements prevent SQL injection
echo $username;
?>
Login to try C/C++/Java/PHP code in the editor
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
$input = "<script>alert('x')</script>Hello";
$forStorage = strip_tags($input);
$forDisplay = htmlspecialchars($forStorage);
echo $forDisplay;
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: