Sanitizing User Input
Remove dangerous characters with htmlspecialchars and filter_input.
Sanitization vs Validation
Validation checks if data meets requirements (and rejects it if not).
Sanitization cleans data by removing or encoding dangerous characters so it's safe to use.
Both are needed — validate first, then sanitize for output.
htmlspecialchars() for HTML Output
Always escape output before inserting into HTML to prevent XSS:
<?php
$name = '<script>alert(1)</script>';
// Dangerous — executes script:
// echo $name;
// Safe:
echo htmlspecialchars($name, ENT_QUOTES | ENT_HTML5, 'UTF-8');
// <script>alert(1)</script>