How do I limit file upload sizes using .htaccess?

To limit file upload sizes using .htaccess, the method depends on whether you want to restrict it at the PHP application level or the Apache web server level. The most common approach is using PHP directives, but there is also a server-level limit you can apply.

Method 1: Using PHP Directives (Most Common).

If your server runs PHP as an Apache module (mod_php), you can set PHP configuration values directly in your .htaccess file . This controls the maximum size PHP will accept for uploaded files and POST data.

Add the following lines to your .htaccess file:

# Maximum size for a single uploaded file

php_value upload_max_filesize 10M

# Maximum size for all POST data (should be larger than upload_max_filesize)

php_value post_max_size 12M

Key points to remember:

  • upload_max_filesize: This is the hard limit for a single file.
  • post_max_size: This must be larger than upload_max_filesize because it includes the file plus any other form data. If you set it too low, the upload will fail even if the file itself is under the limit .
  • Server Compatibility: This method only works if PHP is running as an Apache module (mod_php). If your host uses PHP-FPM (common on modern setups), these directives will cause a 500 Internal Server Error. In that case, you would need to use a .user.ini file or adjust the FPM pool configuration instead.

Method 2: Using Apache is LimitRequestBody(Server-Level).

If you want a hard limit at the Apache level (regardless of PHP settings), you can use the LimitRequestBody directive. This restricts the total size of the HTTP request body in bytes.

# Limit request body to 10 MB (10 * 1024 * 1024 bytes)

LimitRequestBody 10485760

Note: This is a blunt instrument. It will block any request larger than the limit, not just file uploads. It is useful for preventing denial-of-service attacks or enforcing a strict cap, but it might interfere with other large POST requests your application makes.

Quick Verification.

After adding the rules, you can verify the changes by creating a temporary PHP file (e.g., info.php) with the following content and accessing it in your browser:

<?php phpinfo(); ?>

Look for the upload_max_filesize and post_max_size values to confirm they match your .htaccess settings. Remember to delete this file immediately after checking, as it exposes sensitive server information.

 

28 Views