0
0
PHPprogramming~10 mins

Input validation vs sanitization in PHP - Interactive Practice

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

Complete the code to check if the input is a valid email.

PHP
<?php
$email = $_POST['email'];
if (filter_var($email, [1])) {
    echo "Valid email.";
} else {
    echo "Invalid email.";
}
?>
Drag options to blanks, or click blank then click option'
AFILTER_VALIDATE_INT
BFILTER_SANITIZE_EMAIL
CFILTER_VALIDATE_EMAIL
DFILTER_SANITIZE_STRING
Attempts:
3 left
💡 Hint
Common Mistakes
Using FILTER_SANITIZE_EMAIL instead of FILTER_VALIDATE_EMAIL for validation.
2fill in blank
medium

Complete the code to sanitize the input by removing illegal characters from an email.

PHP
<?php
$email = $_POST['email'];
$clean_email = filter_var($email, [1]);
echo $clean_email;
?>
Drag options to blanks, or click blank then click option'
AFILTER_SANITIZE_EMAIL
BFILTER_SANITIZE_STRING
CFILTER_VALIDATE_EMAIL
DFILTER_VALIDATE_URL
Attempts:
3 left
💡 Hint
Common Mistakes
Using FILTER_VALIDATE_EMAIL when sanitization is needed.
3fill in blank
hard

Fix the error in the code to properly validate an integer input.

PHP
<?php
$age = $_POST['age'];
if (filter_var($age, [1])) {
    echo "Valid age.";
} else {
    echo "Invalid age.";
}
?>
Drag options to blanks, or click blank then click option'
AFILTER_SANITIZE_NUMBER_INT
BFILTER_VALIDATE_INT
CFILTER_VALIDATE_EMAIL
DFILTER_SANITIZE_STRING
Attempts:
3 left
💡 Hint
Common Mistakes
Using FILTER_SANITIZE_NUMBER_INT instead of FILTER_VALIDATE_INT for validation.
4fill in blank
hard

Fill both blanks to create a sanitized and validated username input.

PHP
<?php
$username = $_POST['username'];
$clean_username = filter_var($username, [1]);
if (preg_match([2], $clean_username)) {
    echo "Valid username.";
} else {
    echo "Invalid username.";
}
?>
Drag options to blanks, or click blank then click option'
AFILTER_SANITIZE_STRING
B/^[a-zA-Z0-9_]{3,20}$/
C/^[\w]{3,20}$/
DFILTER_VALIDATE_EMAIL
Attempts:
3 left
💡 Hint
Common Mistakes
Using FILTER_VALIDATE_EMAIL for username validation.
Not sanitizing before validating.
5fill in blank
hard

Fill all three blanks to sanitize and validate a URL input.

PHP
<?php
$url = $_POST['url'];
$clean_url = filter_var($url, [1]);
if (filter_var($clean_url, [2]) && preg_match([3], $clean_url)) {
    echo "Valid URL.";
} else {
    echo "Invalid URL.";
}
?>
Drag options to blanks, or click blank then click option'
AFILTER_SANITIZE_URL
BFILTER_VALIDATE_URL
C/^https?:\/\//
DFILTER_SANITIZE_STRING
Attempts:
3 left
💡 Hint
Common Mistakes
Skipping sanitization before validation.
Not checking the URL scheme with regex.