0
0
PHPprogramming~5 mins

File upload security risks in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: File upload security risks
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

As the number of files increases, the code does more checks and moves more files.

Input Size (n)Approx. Operations
10About 10 checks and moves
100About 100 checks and moves
1000About 1000 checks and moves

Pattern observation: The work grows directly with the number of files; double the files, double the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to process files grows linearly with how many files are uploaded.

Common Mistake

[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.

Interview Connect

Understanding how file upload handling scales helps you write safer and more efficient code, a skill valuable in many real projects.

Self-Check

"What if we added a nested loop to scan inside each file's contents? How would the time complexity change?"