$_FILES for file uploads in PHP - Time & Space Complexity
When handling file uploads in PHP using $_FILES, it's important to understand how the processing time changes as more files are uploaded.
We want to know how the time to handle files grows when the number of uploaded files increases.
Analyze the time complexity of the following code snippet.
// Loop through uploaded files
foreach ($_FILES['userfiles']['tmp_name'] as $index => $tmpName) {
// Move each uploaded file to a new location
move_uploaded_file($tmpName, 'uploads/' . $_FILES['userfiles']['name'][$index]);
}
This code moves each uploaded file from its temporary location to a permanent folder.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each uploaded file and moving it.
- How many times: Once for each file uploaded (depends on number of files).
As the number of files increases, the number of move operations increases linearly.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 files | 10 moves |
| 100 files | 100 moves |
| 1000 files | 1000 moves |
Pattern observation: The work grows directly with the number of files.
Time Complexity: O(n)
This means the time to process uploads grows in a straight line as you add more files.
[X] Wrong: "Processing multiple files happens instantly or all at once regardless of count."
[OK] Correct: Each file requires its own move operation, so more files mean more work and more time.
Understanding how file upload handling scales helps you write efficient code and explain your reasoning clearly in interviews.
"What if we processed files in parallel instead of one by one? How would the time complexity change?"