Forms & User Input · Lesson 5 of 6
Sanitizing Input
Validate input for meaning and escape output for its destination context.
Lesson
Validation asks whether input is allowed; sanitization transforms a value; output escaping protects a specific destination such as HTML. These are not interchangeable. Preserve validated data in its appropriate form, use parameterized SQL for database values, and escape text at the point it is inserted into HTML.
For HTML, htmlspecialchars with quotes enabled and UTF-8 is a suitable text-context escape.
Further guidance
Treat every submitted field and uploaded file as untrusted. Validate type, length, allowed values, and request method on the server; use CSRF protection for state changes. Escape values for their output context, and never use browser validation as the only safeguard.
Practice task: Create a fresh example for Sanitizing Input. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.
Code examples
Sanitizing Input
PHP
$untrusted = '<script>alert(1)</script>';
echo htmlspecialchars($untrusted, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
Expected output
<script>alert(1)</script>
Key points
- Validate input for meaning and escape output for its destination context.
- Validate input on the server before processing it.
- Escape output for its context and protect state-changing forms from CSRF.
Your learning progress
Finish this lesson
Optional practice
PHP playground
This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.
Execution is disabled. No code is sent to a server.