0
0
PHPprogramming~10 mins

Input validation and sanitization in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to get user input from a POST request safely.

PHP
<?php
$user_input = $_POST[[1]];
?>
Drag options to blanks, or click blank then click option'
Ausername
B"username"
C"user_input"
Dinput
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around the key causes a syntax error.
Using a wrong key name returns null.
2fill in blank
medium

Complete the code to sanitize the user input as a string.

PHP
<?php
$clean_input = filter_var($user_input, [1]);
?>
Drag options to blanks, or click blank then click option'
AFILTER_SANITIZE_STRING
BFILTER_VALIDATE_EMAIL
CFILTER_SANITIZE_EMAIL
DFILTER_VALIDATE_INT
Attempts:
3 left
💡 Hint
Common Mistakes
Using validation filters instead of sanitization filters.
Choosing filters meant for emails or numbers.
3fill in blank
hard

Fix the error in the code to validate if input is an integer.

PHP
<?php
if (filter_var($input, [1]) === false) {
    echo "Invalid number.";
}
?>
Drag options to blanks, or click blank then click option'
AFILTER_VALIDATE_INT
BFILTER_SANITIZE_NUMBER_INT
CFILTER_VALIDATE_BOOLEAN
DFILTER_SANITIZE_STRING
Attempts:
3 left
💡 Hint
Common Mistakes
Using sanitization filters instead of validation filters.
Confusing boolean validation with integer validation.
4fill in blank
hard

Fill both blanks to sanitize and then validate an email input.

PHP
<?php
$email = filter_var($raw_email, [1]);
if (filter_var($email, [2]) === false) {
    echo "Invalid email.";
}
?>
Drag options to blanks, or click blank then click option'
AFILTER_SANITIZE_EMAIL
BFILTER_VALIDATE_INT
CFILTER_VALIDATE_EMAIL
DFILTER_SANITIZE_STRING
Attempts:
3 left
💡 Hint
Common Mistakes
Validating before sanitizing.
Using wrong filters for email validation.
5fill in blank
hard

Fill all three blanks to create a sanitized array of usernames longer than 3 characters.

PHP
<?php
$usernames = ['alice', 'bob', 'eve123', 'jo'];
$filtered = array_filter(array_map(function($name) {
    return filter_var($name, [1]);
}, $usernames), function($name) {
    return strlen($name) [2] [3];
});
?>
Drag options to blanks, or click blank then click option'
AFILTER_SANITIZE_STRING
B>
C3
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using validation filters instead of sanitization.
Using wrong comparison operators or values.