0
0
PHPprogramming~20 mins

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

Choose your learning style9 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.