0
0
PHPprogramming~30 mins

Input validation vs sanitization in PHP - Hands-On Comparison

Choose your learning style9 modes available
Input validation vs sanitization
📖 Scenario: You are building a simple PHP script that accepts user input for a username and email address. You want to make sure the input is safe and correct before using it.
🎯 Goal: Learn how to validate and sanitize user input in PHP to prevent errors and security issues.
📋 What You'll Learn
Create variables with exact user input values
Add a variable to hold a validation rule
Use PHP functions to validate and sanitize input
Print the final cleaned and validated input
💡 Why This Matters
🌍 Real World
Validating and sanitizing user input is essential for web forms to prevent errors and security risks like SQL injection or broken data.
💼 Career
Many programming jobs require you to handle user input safely. Understanding validation and sanitization is a key skill for backend and full-stack developers.
Progress0 / 4 steps
1
DATA SETUP: Create user input variables
Create two variables called $username and $email with these exact values: 'John_Doe!' for $username and 'john.doe@example.com' for $email.
PHP
Need a hint?

Use = to assign the exact strings to the variables.

2
CONFIGURATION: Define validation rule for username
Create a variable called $username_pattern and set it to the regular expression /^[a-zA-Z0-9_]+$/ to allow only letters, numbers, and underscores in the username.
PHP
Need a hint?

Use single quotes around the regex pattern.

3
CORE LOGIC: Validate and sanitize inputs
Use preg_match with $username_pattern to check if $username is valid. If valid, keep it; otherwise, set $username to "Invalid username". Then sanitize $email using filter_var with FILTER_SANITIZE_EMAIL and store the result back in $email.
PHP
Need a hint?

Use if (!preg_match(...)) to check invalid username.

4
OUTPUT: Display the cleaned and validated input
Print the values of $username and $email using echo with labels exactly as: "Username: " and "Email: ".
PHP
Need a hint?

Use echo with double quotes and newline \n.