Bird
Raised Fist0
PHPprogramming~10 mins

Input validation vs sanitization in PHP - Visual Side-by-Side Comparison

Choose your learning style10 modes available
Concept Flow - Input validation vs sanitization
User Input Received
↓
Input Validation
Yes / No↓
Input OK
↓
Input Sanitization
↓
Safe Input Used
First, the program checks if the input meets rules (validation). If yes, it cleans the input (sanitization) before use. If no, it rejects the input.
Execution Sample
PHP
<?php
$input = "<script>alert('Hi')</script>";
if (filter_var($input, FILTER_VALIDATE_EMAIL)) {
  $safe = filter_var($input, FILTER_SANITIZE_EMAIL);
  echo $safe;
} else {
  echo "Invalid input";
}
?>
This PHP code checks if input is a valid email. If yes, it cleans it. If no, it shows 'Invalid input'.
Execution Table
StepActionInput ValueValidation ResultSanitized ValueOutput
1Receive input<script>alert('Hi')</script>Not checked yetNot sanitized yetNo output
2Validate input as email<script>alert('Hi')</script>False (invalid email)N/ANo output
3Check validation resultN/AFalseN/AGo to else branch
4Output invalid messageN/AN/AN/AInvalid input
5EndN/AN/AN/AProgram stops
💡 Input fails validation, so sanitization is skipped and 'Invalid input' is output.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 4Final
$inputN/A<script>alert('Hi')</script><script>alert('Hi')</script><script>alert('Hi')</script><script>alert('Hi')</script>
Validation ResultN/AN/AFalseFalseFalse
$safeN/AN/AN/AN/AN/A
OutputN/AN/AN/AInvalid inputInvalid input
Key Moments - 3 Insights
Why does the program reject the input before sanitizing it?
Because validation fails (see execution_table step 2 and 3), the program does not sanitize unsafe input to avoid using bad data.
Is sanitization enough to trust input?
No, sanitization cleans input but does not check if input is correct format. Validation must happen first (see concept_flow).
What happens if input passes validation?
If validation is true, sanitization cleans input before use (not shown in this example but implied in concept_flow).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the validation result at step 2?
ATrue (valid email)
BFalse (invalid email)
CNot checked yet
DError occurred
💡 Hint
Check the 'Validation Result' column at step 2 in execution_table.
At which step does the program output 'Invalid input'?
AStep 4
BStep 1
CStep 3
DStep 5
💡 Hint
Look at the 'Output' column in execution_table to find when 'Invalid input' appears.
If the input was a valid email, what would happen next according to the concept_flow?
AProgram would crash
BInput would be rejected immediately
CInput would be sanitized before use
DNo action would be taken
💡 Hint
Refer to the concept_flow diagram showing validation then sanitization.
Concept Snapshot
Input validation checks if data meets rules (like format).
Sanitization cleans data to remove harmful parts.
Validate first, then sanitize.
Reject input if validation fails.
Use sanitized input safely in your program.
Full Transcript
This example shows how PHP handles input validation and sanitization. First, the program receives user input. It then checks if the input is a valid email address using validation. If the input is invalid, the program rejects it and outputs 'Invalid input'. If the input were valid, it would be sanitized to remove unsafe characters before use. This process helps keep programs safe by ensuring only good data is used. Validation is about correctness, sanitization is about safety. Both steps are important and happen in order.

Practice

(1/5)
1. What is the main purpose of input validation in PHP?
easy
A. To remove unwanted characters from the input
B. To store input data in a database
C. To check if the input data meets expected rules or format
D. To encrypt the input data for security

Solution

  1. Step 1: Understand input validation meaning

    Input validation means checking if the data entered by the user follows the expected format or rules, like checking if an email looks like an email.
  2. Step 2: Compare with other options

    Removing unwanted characters is sanitization, storing data is unrelated, and encrypting is a different security step.
  3. Final Answer:

    To check if the input data meets expected rules or format -> Option C
  4. Quick Check:

    Validation = Check input format [OK]
Hint: Validation means checking input correctness, not cleaning it [OK]
Common Mistakes:
  • Confusing validation with sanitization
  • Thinking validation changes the input
  • Assuming validation stores or encrypts data
2. Which PHP function is used primarily for sanitizing an email input?
easy
A. filter_var($email, FILTER_VALIDATE_EMAIL)
B. trim($email)
C. htmlspecialchars($email)
D. filter_var($email, FILTER_SANITIZE_EMAIL)

Solution

  1. Step 1: Identify sanitization function for email

    FILTER_SANITIZE_EMAIL removes illegal characters from an email string, cleaning it.
  2. Step 2: Differentiate from validation and other functions

    FILTER_VALIDATE_EMAIL checks if email is valid (validation). htmlspecialchars escapes HTML, trim removes spaces.
  3. Final Answer:

    filter_var($email, FILTER_SANITIZE_EMAIL) -> Option D
  4. Quick Check:

    Sanitize email = FILTER_SANITIZE_EMAIL [OK]
Hint: Sanitize email uses FILTER_SANITIZE_EMAIL, not VALIDATE [OK]
Common Mistakes:
  • Using FILTER_VALIDATE_EMAIL for sanitization
  • Confusing htmlspecialchars with sanitization
  • Ignoring trimming spaces as sanitization
3. What will be the output of this PHP code?
$input = "user@example.com";
$sanitized = filter_var($input, FILTER_SANITIZE_EMAIL);
echo $sanitized;
medium
A. alert('Hi');user@example.com
B. user@example.com
C. <script>alert('Hi');</script>user@example.com
D. Syntax error

Solution

  1. Step 1: Understand FILTER_SANITIZE_EMAIL effect

    This filter removes illegal characters but keeps some like apostrophes and semicolons, so the alert part remains partially.
  2. Step 2: Analyze input and output

    The <script> tags are removed, but alert('Hi'); remains before the email, so output is alert('Hi');user@example.com.
  3. Final Answer:

    alert('Hi');user@example.com -> Option A
  4. Quick Check:

    Sanitize email removes tags but keeps some chars [OK]
Hint: Sanitize email removes tags but may keep some symbols [OK]
Common Mistakes:
  • Expecting full removal of script content
  • Confusing sanitization with escaping HTML
  • Assuming syntax error from special chars
4. Identify the error in this PHP code snippet for validating an integer input:
$age = "25";
if (filter_var($age, FILTER_SANITIZE_NUMBER_INT)) {
  echo "Valid age";
} else {
  echo "Invalid age";
}
medium
A. Using FILTER_SANITIZE_NUMBER_INT instead of FILTER_VALIDATE_INT
B. Missing semicolon after echo statements
C. Incorrect variable name in filter_var
D. No error, code is correct

Solution

  1. Step 1: Check filter used for validation

    FILTER_SANITIZE_NUMBER_INT cleans input but does not validate if it's a proper integer.
  2. Step 2: Correct filter for validation

    FILTER_VALIDATE_INT should be used to check if input is a valid integer.
  3. Final Answer:

    Using FILTER_SANITIZE_NUMBER_INT instead of FILTER_VALIDATE_INT -> Option A
  4. Quick Check:

    Validation needs FILTER_VALIDATE_INT, not sanitize [OK]
Hint: Validation uses FILTER_VALIDATE_INT, not sanitize filters [OK]
Common Mistakes:
  • Confusing sanitize and validate filters
  • Ignoring filter_var second argument importance
  • Assuming sanitize also validates
5. You want to accept a username input that must be alphanumeric and between 5 to 10 characters. Which approach correctly combines validation and sanitization in PHP?
hard
A. Validate with FILTER_VALIDATE_REGEXP for pattern, then sanitize with FILTER_SANITIZE_STRING
B. Sanitize with FILTER_SANITIZE_STRING, then validate length and ctype_alnum
C. Only sanitize with FILTER_SANITIZE_STRING, no validation needed
D. Only validate length with strlen, ignore sanitization

Solution

  1. Step 1: Understand validation and sanitization order

    First sanitize the input to remove unwanted characters using FILTER_SANITIZE_STRING.
  2. Step 2: Validate length and alphanumeric

    Then validate the length with strlen and check if the string is alphanumeric using ctype_alnum.
  3. Final Answer:

    Sanitize with FILTER_SANITIZE_STRING, then validate length and ctype_alnum -> Option B
  4. Quick Check:

    Sanitize first, then validate pattern and length [OK]
Hint: Sanitize first, then validate length and alphanumeric [OK]
Common Mistakes:
  • Validating before sanitizing
  • Skipping sanitization and trusting validation only
  • Ignoring length check in validation
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard