File upload security risks in PHP - Time & Space Complexity
When handling file uploads in PHP, it's important to understand how the code's work grows as more files or larger files are processed.
We want to see how the time to check and save files changes with input size.
Analyze the time complexity of the following code snippet.
// Process multiple uploaded files
foreach ($_FILES['uploads']['tmp_name'] as $index => $tmpName) {
$fileName = $_FILES['uploads']['name'][$index];
$fileType = $_FILES['uploads']['type'][$index];
// Simple check for allowed types
if (in_array($fileType, ['image/jpeg', 'image/png'])) {
move_uploaded_file($tmpName, '/uploads/' . $fileName);
}
}
This code loops through uploaded files, checks their type, and moves allowed files to a folder.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each uploaded file to check and move it.
- How many times: Once for each file uploaded (depends on number of files).
As the number of files increases, the code does more checks and moves more files.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and moves |
| 100 | About 100 checks and moves |
| 1000 | About 1000 checks and moves |
Pattern observation: The work grows directly with the number of files; double the files, double the work.
Time Complexity: O(n)
This means the time to process files grows linearly with how many files are uploaded.
[X] Wrong: "Checking file types or moving files happens instantly no matter how many files there are."
[OK] Correct: Each file requires a check and a move operation, so more files mean more work and more time.
Understanding how file upload handling scales helps you write safer and more efficient code, a skill valuable in many real projects.
"What if we added a nested loop to scan inside each file's contents? How would the time complexity change?"