---
title: Limit Upload File Size And Count
impact: MEDIUM
impactDescription: prevents Denial of Service (DoS) attacks by resource exhaustion
tags: upload, file-size, dos, limits, security, php
---

## Limit Upload File Size And Count

Allowing unlimited file uploads can quickly exhaust server disk space, memory, and bandwidth, leading to a Denial of Service (DoS). It is critical to enforce strict limits on the number of files, their size, and their types.

**Incorrect (trusting default or no limits):**

```php
// Standard PHP - No manual size checking
$file = $_FILES['avatar'];
move_uploaded_file($file['tmp_name'], 'uploads/' . $file['name']);

// VULNERABLE: No validation of count or type
foreach ($_FILES['documents'] as $file) {
    // Process all files without limit
}
```

**Correct (explicit limits in PHP and Application):**

```php
/**
 * 1. Configure PHP settings (php.ini or .user.ini)
 * upload_max_filesize = 5M
 * post_max_size = 8M
 * max_file_uploads = 5
 */

// 2. Manual check in plain PHP
$maxSize = 5 * 1024 * 1024; // 5MB
if ($_FILES['avatar']['size'] > $maxSize) {
    die("File exceeds size limit");
}

// 3. Using Laravel Validation (Recommended)
$request->validate([
    'avatar' => 'required|file|image|max:5120', // size in kilobytes
    'documents' => 'required|array|max:5',     // max 5 files
    'documents.*' => 'file|mimes:pdf,docx|max:10240' // max 10MB per file
]);
```

**Recommended limits:**
- **Images**: 2MB - 10MB
- **Documents**: 5MB - 20MB
- **Max Items**: 5-10 files per request.
- **Whitelist**: Always use `mimes` or `mimetypes` validation to only allow expected extensions (e.g., `jpg, png, pdf`).

**Why these limits matter?**
- Prevents disk-filling attacks.
- Reduces memory usage during image processing or virus scanning.
- Minimizes the attack surface for file-based exploits.

**Tools:** PHP Internal Config, Laravel Validator, Symfony Validator, Nginx `client_max_body_size`
