PHP
Intermediate
122 helpful
227 views

Handle File Upload Size Limits in Web Applications

Published Apr 24, 2025 Last updated Jun 16, 2025

Problem

Users cannot upload large files through web forms, getting errors like "File too large" or uploads failing silently.

Root Cause

File upload limits are controlled by multiple layers: web server configuration, PHP settings, and application-level restrictions. Each layer can impose its own limits.

Solution

Configure file upload limits at multiple levels:

Step 1: PHP Configuration (php.ini)

; Maximum allowed size for uploaded files
upload_max_filesize = 50M

; Maximum size of POST data
post_max_size = 50M

; Maximum execution time for scripts
max_execution_time = 300

; Maximum input time
max_input_time = 300

; Memory limit
memory_limit = 256M

Step 2: Web Server Configuration

For Apache (.htaccess)

# Increase upload limits
php_value upload_max_filesize 50M
php_value post_max_size 50M
php_value max_execution_time 300
php_value max_input_time 300

For Nginx

server {
    # Maximum allowed size of client request body
    client_max_body_size 50M;

    # Timeout for reading client request body
    client_body_timeout 300s;
}

Step 3: Application-Level Handling

<?php
// Check upload errors
if ($_FILES['upload']['error'] !== UPLOAD_ERR_OK) {
    switch ($_FILES['upload']['error']) {
        case UPLOAD_ERR_INI_SIZE:
            $error = 'File exceeds upload_max_filesize directive';
            break;
        case UPLOAD_ERR_FORM_SIZE:
            $error = 'File exceeds MAX_FILE_SIZE directive';
            break;
        case UPLOAD_ERR_PARTIAL:
            $error = 'File was only partially uploaded';
            break;
        case UPLOAD_ERR_NO_FILE:
            $error = 'No file was uploaded';
            break;
        default:
            $error = 'Unknown upload error';
            break;
    }
    throw new Exception($error);
}

// Validate file size
$maxSize = 50 * 1024 * 1024; // 50MB in bytes
if ($_FILES['upload']['size'] > $maxSize) {
    throw new Exception('File size exceeds limit');
}

// Validate file type
$allowedTypes = ['image/jpeg', 'image/png', 'application/pdf'];
if (!in_array($_FILES['upload']['type'], $allowedTypes)) {
    throw new Exception('File type not allowed');
}
?>

Step 4: Frontend Progress Indication

// Show upload progress
function uploadFile(file) {
    const formData = new FormData();
    formData.append('upload', file);

    fetch('/upload.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        console.log('Upload successful:', data);
    })
    .catch(error => {
        console.error('Upload failed:', error);
    });
}
Back to Solutions
1