Input validation and sanitization in PHP - Time & Space Complexity
When checking and cleaning user input in PHP, it is important to know how the time needed grows as the input gets bigger.
We want to see how the work done changes when the input size changes.
Analyze the time complexity of the following code snippet.
function sanitizeInput(array $inputs): array {
$cleaned = [];
foreach ($inputs as $key => $value) {
$trimmed = trim($value);
$safe = htmlspecialchars($trimmed, ENT_QUOTES, 'UTF-8');
$cleaned[$key] = $safe;
}
return $cleaned;
}
This code takes an array of user inputs, trims spaces, and converts special characters to safe HTML entities.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each input item once.
- How many times: Once for each input element in the array.
As the number of inputs grows, the work grows in a straight line because each input is handled one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 times the work |
| 100 | About 100 times the work |
| 1000 | About 1000 times the work |
Pattern observation: The work increases evenly as input size increases.
Time Complexity: O(n)
This means the time to clean inputs grows directly with the number of inputs.
[X] Wrong: "Sanitizing input is instant no matter how many items there are."
[OK] Correct: Each input needs its own cleaning step, so more inputs mean more work.
Understanding how input validation scales helps you write secure and efficient code, a skill valued in many coding challenges and real projects.
"What if we added nested arrays inside inputs? How would the time complexity change?"
Practice
Solution
Step 1: Understand input validation
Input validation means checking if the data entered by a user meets certain rules and is safe to use.Step 2: Identify the purpose
The main goal is to ensure data is correct and safe before using it in the program.Final Answer:
To check if the input data is correct and safe -> Option AQuick Check:
Input validation = check correctness and safety [OK]
- Confusing validation with data storage
- Thinking validation displays data
- Assuming validation creates variables
Solution
Step 1: Understand sanitization vs validation
Sanitization cleans data by removing unwanted characters, validation checks if data is valid.Step 2: Identify correct filter for sanitizing email
FILTER_SANITIZE_EMAIL removes illegal characters from email input.Final Answer:
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL); -> Option DQuick Check:
Sanitize email = FILTER_SANITIZE_EMAIL [OK]
- Using FILTER_VALIDATE_EMAIL for sanitization
- Using FILTER_VALIDATE_INT for email
- Using FILTER_SANITIZE_STRING for email
$input = ""; $clean = filter_var($input, FILTER_SANITIZE_STRING); echo $clean;
Solution
Step 1: Understand FILTER_SANITIZE_STRING behavior
This filter removes tags and encodes or strips HTML tags from the string.Step 2: Apply filter to input
The input contains a script tag; sanitizing removes the <script> and </script> tags, leaving only "alert('Hi');".Final Answer:
alert('Hi'); -> Option CQuick Check:
Sanitize string removes tags = alert('Hi'); [OK]
- Expecting tags to remain
- Confusing sanitization with validation
- Thinking code runs or causes error
$age = $_POST['age'];
if (filter_var($age, FILTER_SANITIZE_INT)) {
echo "Valid age";
} else {
echo "Invalid age";
}Solution
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.Step 2: Correct filter for validation
To check if input is a valid integer, use FILTER_VALIDATE_INT instead of FILTER_SANITIZE_INT.Final Answer:
FILTER_SANITIZE_INT should be FILTER_VALIDATE_INT -> Option BQuick Check:
Validation needs FILTER_VALIDATE_INT, not sanitize [OK]
- Confusing sanitize with validate filters
- Ignoring filter_var() return values
- Assuming sanitize validates input
filter_var() and a custom pattern?Solution
Step 1: Understand the requirement
The username must only have letters, numbers, and underscores, so a regular expression is needed to check this pattern.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.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.Final Answer:
Code using FILTER_VALIDATE_REGEXP with pattern '/^[a-zA-Z0-9_]+$/' -> Option AQuick Check:
Validate username with FILTER_VALIDATE_REGEXP + regex [OK]
- Using sanitize instead of validate
- Using email or int filters for username
- Not using regex for pattern matching
Ready to prove it?
Pass the test and this pattern moves unknown
