Menu

Sanitization, Validation, and Escaping

Always apply in this order: sanitize, validate, escape

🧹 Sanitization (Cleaning Input)

Purpose: Remove or modify dangerous content while preserving useful data. Sanitization transforms input to make it safe, but may lose information in the process. Needing to remove characters through sanitizing should not trigger any error response; save that for validation.

When to Use Sanitization

  • Username: Remove special characters, keep only alphanumeric
  • Phone: Keep only digits, +, -, (, ), and spaces
  • Email: Remove invalid email characters
  • Search query: Remove HTML but keep most text

Warning: Sanitization alone is NOT enough! You must still escape output and validate input.

⚠️ Validation Mismatch (Request Tampering)

Vulnerability: Client-side validation only allows letters (a-z), but server-side validation allows letters AND numbers!

Try entering numbers in the form – they'll be blocked by input filter pattern attributes and JavaScript. Then use browser DevTools, curl, or an attack proxy to bypass client validation.

How to Test Request Tampering

  1. Browser DevTools: Open DevTools (F12), go to Elements tab, find the input field, and remove or modify the pattern="[a-z]+" attribute
  2. Using curl: curl -X POST -d "username=user123" https://robot.hakr.site/validation.php
  3. Burp Suite / ZAP: Intercept the request and modify the username parameter to include numbers

Lesson: Never trust client-side validation! It's only for UX; Always validate on the server with the same rules.

🔒 Escaping (Safe Output)

Purpose: Display potentially dangerous content safely by encoding special characters.

Escaping preserves the original data but renders it harmless in the output context.

Escaping Best Practices

  • Always escape untrusted data before displaying it
  • Use the right escaping function for the context (HTML, JS, URL, SQL)
  • Use ENT_QUOTES | ENT_HTML5 flags with htmlspecialchars()
  • Never skip escaping because you "sanitized" the input earlier
  • Defence in depth:: Apply all measures: Sanitize if needed, validate input, AND escape output. Don't skip escaping just because you validated.