Bird
Raised Fist0
PHPprogramming~20 mins

Input validation and sanitization in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Input Validation Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this PHP code with input sanitization?

Consider the following PHP code that sanitizes user input before outputting it. What will be printed?

PHP
<?php
$user_input = "<script>alert('XSS');</script>";
$sanitized = filter_var($user_input, FILTER_SANITIZE_STRING);
echo $sanitized;
?>
A&lt;script&gt;alert('XSS');&lt;/script&gt;
Balert('XSS');&lt;/script&gt;
Calert('XSS');
DSyntaxError
Attempts:
2 left
💡 Hint

FILTER_SANITIZE_STRING removes tags but keeps the text inside.

❓ Predict Output
intermediate
2:00remaining
What error does this PHP code raise when validating an email?

What error will this PHP code produce when validating an invalid email?

PHP
<?php
$email = "invalid-email@";
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    throw new Exception("Invalid email format");
}
echo "Valid email";
?>
AWarning: filter_var expects parameter 2 to be int
BException with message 'Invalid email format'
CParse error
DValid email
Attempts:
2 left
💡 Hint

FILTER_VALIDATE_EMAIL returns false if the email is invalid.

🔧 Debug
advanced
2:00remaining
Why does this PHP code fail to sanitize input correctly?

Find the reason why this PHP code does not sanitize the input as expected.

PHP
<?php
$input = "<b>Hello</b>";
$clean = filter_var($input, FILTER_SANITIZE_EMAIL);
echo $clean;
?>
AFILTER_SANITIZE_EMAIL removes all characters except letters, digits and !#$%&'*+-/=?^_`{|}~@.[] so tags remain
BFILTER_SANITIZE_EMAIL removes tags but leaves text inside
CFILTER_SANITIZE_EMAIL is deprecated and causes a warning
DThe variable $input is not defined
Attempts:
2 left
💡 Hint

Check what FILTER_SANITIZE_EMAIL actually removes.

❓ Predict Output
advanced
2:00remaining
What is the output of this PHP code using htmlspecialchars?

What will this PHP code print?

PHP
<?php
$input = "<a href='test'>Test</a> & \"Quotes\"";
$escaped = htmlspecialchars($input, ENT_QUOTES);
echo $escaped;
?>
A<a href='test'>Test</a> & "Quotes"
BSyntaxError
C&lt;a href='test'&gt;Test&lt;/a&gt; & "Quotes"
D&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt; &amp; &quot;Quotes&quot;
Attempts:
2 left
💡 Hint

htmlspecialchars converts special characters to HTML entities.

🧠 Conceptual
expert
2:00remaining
Which PHP function best prevents SQL injection by sanitizing input?

Which of the following PHP functions is the best choice to prevent SQL injection attacks by properly sanitizing user input before using it in SQL queries?

Amysqli_real_escape_string()
Bhtmlspecialchars()
Cfilter_var() with FILTER_SANITIZE_STRING
Daddslashes()
Attempts:
2 left
💡 Hint

Think about functions designed specifically for SQL context.

Practice

(1/5)
1. What is the main purpose of input validation in PHP?
easy
A. To check if the input data is correct and safe
B. To store data in a database
C. To display data on the screen
D. To create new variables automatically

Solution

  1. Step 1: Understand input validation

    Input validation means checking if the data entered by a user meets certain rules and is safe to use.
  2. Step 2: Identify the purpose

    The main goal is to ensure data is correct and safe before using it in the program.
  3. Final Answer:

    To check if the input data is correct and safe -> Option A
  4. Quick Check:

    Input validation = check correctness and safety [OK]
Hint: Validation means checking data correctness and safety [OK]
Common Mistakes:
  • Confusing validation with data storage
  • Thinking validation displays data
  • Assuming validation creates variables
2. Which of the following is the correct syntax to sanitize an email input in PHP?
easy
A. $email = filter_var($_POST['email'], FILTER_SANITIZE_STRING);
B. $email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
C. $email = filter_var($_POST['email'], FILTER_VALIDATE_INT);
D. $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);

Solution

  1. Step 1: Understand sanitization vs validation

    Sanitization cleans data by removing unwanted characters, validation checks if data is valid.
  2. Step 2: Identify correct filter for sanitizing email

    FILTER_SANITIZE_EMAIL removes illegal characters from email input.
  3. Final Answer:

    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); -> Option D
  4. Quick Check:

    Sanitize email = FILTER_SANITIZE_EMAIL [OK]
Hint: Sanitize email uses FILTER_SANITIZE_EMAIL in filter_var() [OK]
Common Mistakes:
  • Using FILTER_VALIDATE_EMAIL for sanitization
  • Using FILTER_VALIDATE_INT for email
  • Using FILTER_SANITIZE_STRING for email
3. What will be the output of this PHP code?
$input = "";
$clean = filter_var($input, FILTER_SANITIZE_STRING);
echo $clean;
medium
A. alert('Hi');</script>
B. <script>alert('Hi');</script>
C. alert('Hi');
D. Syntax error

Solution

  1. Step 1: Understand FILTER_SANITIZE_STRING behavior

    This filter removes tags and encodes or strips HTML tags from the string.
  2. Step 2: Apply filter to input

    The input contains a script tag; sanitizing removes the <script> and </script> tags, leaving only "alert('Hi');".
  3. Final Answer:

    alert('Hi'); -> Option C
  4. Quick Check:

    Sanitize string removes tags = alert('Hi'); [OK]
Hint: FILTER_SANITIZE_STRING removes HTML tags from input [OK]
Common Mistakes:
  • Expecting tags to remain
  • Confusing sanitization with validation
  • Thinking code runs or causes error
4. Identify the error in this PHP code snippet for validating an integer input:
$age = $_POST['age'];
if (filter_var($age, FILTER_SANITIZE_INT)) {
    echo "Valid age";
} else {
    echo "Invalid age";
}
medium
A. Missing semicolon after echo statements
B. FILTER_SANITIZE_INT should be FILTER_VALIDATE_INT
C. Using $_POST without quotes
D. filter_var() cannot validate integers

Solution

  1. Step 1: Understand difference between sanitize and validate

    FILTER_SANITIZE_INT cleans input by removing non-numeric characters but does not validate if input is a valid integer.
  2. Step 2: Correct filter for validation

    To check if input is a valid integer, use FILTER_VALIDATE_INT instead of FILTER_SANITIZE_INT.
  3. Final Answer:

    FILTER_SANITIZE_INT should be FILTER_VALIDATE_INT -> Option B
  4. Quick Check:

    Validation needs FILTER_VALIDATE_INT, not sanitize [OK]
Hint: Use FILTER_VALIDATE_INT to check integers, not sanitize [OK]
Common Mistakes:
  • Confusing sanitize with validate filters
  • Ignoring filter_var() return values
  • Assuming sanitize validates input
5. You want to accept a username that only contains letters, numbers, and underscores. Which PHP code correctly validates this input using filter_var() and a custom pattern?
hard
A. $username = $_POST['username']; if (filter_var($username, FILTER_VALIDATE_REGEXP, ['options' => ['regexp' => '/^[a-zA-Z0-9_]+$/']])) { echo "Valid username"; } else { echo "Invalid username"; }
B. $username = $_POST['username']; if (filter_var($username, FILTER_SANITIZE_STRING)) { echo "Valid username"; } else { echo "Invalid username"; }
C. $username = $_POST['username']; if (filter_var($username, FILTER_VALIDATE_EMAIL)) { echo "Valid username"; } else { echo "Invalid username"; }
D. $username = $_POST['username']; if (filter_var($username, FILTER_VALIDATE_INT)) { echo "Valid username"; } else { echo "Invalid username"; }

Solution

  1. Step 1: Understand the requirement

    The username must only have letters, numbers, and underscores, so a regular expression is needed to check this pattern.
  2. Step 2: Use FILTER_VALIDATE_REGEXP with correct pattern

    FILTER_VALIDATE_REGEXP allows validating input against a regex pattern. The pattern '/^[a-zA-Z0-9_]+$/' matches only allowed characters.
  3. Step 3: Eliminate distractors

    The incorrect options use filters for integer validation, string sanitization, or email validation, none of which enforce the specific pattern of letters, numbers, and underscores.
  4. Final Answer:

    Code using FILTER_VALIDATE_REGEXP with pattern '/^[a-zA-Z0-9_]+$/' -> Option A
  5. Quick Check:

    Validate username with FILTER_VALIDATE_REGEXP + regex [OK]
Hint: Use FILTER_VALIDATE_REGEXP with regex for custom pattern validation [OK]
Common Mistakes:
  • Using sanitize instead of validate
  • Using email or int filters for username
  • Not using regex for pattern matching
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