Increase size limit when uploading files PHP, Nginx and Apache

When we upload files through PHP, there are usually restrictions on the simultaneous number of them, and more than anything on the maximum size per file that we are allowed to upload. A very common default maximum size value is around 2 MB per file, and in most scenarios this is too low a value. Either using Apache or Nginx together with PHP, you can modify this behavior without much technical knowledge.

Modify limit in an environment with Apache and PHP

We have to modify the upload_max_filesize and post_max_size directives in our php.ini, for example:

upload_max_filesize = 50M
post_max_size = 55M

With this, the maximum size is approximately 50 MB. We only have to restart Apache.

On systems with Systemd:

sudo systemctl restart apache2

In other systems:

sudo service apache2 restart

Read the footnote on the units of measurement and on the difference in size between the two previous directives.

Increase limit if we use Nginx, PHP and PHP-FPM

Things change a bit when we use Nginx, since in order to increase the maximum size we have to do one more step, otherwise it will not work if we only modify the PHP directives.

We use the upload_max_filesize and post_max_size directives, as with Apache, in the php.ini file found in /etc/php/7.*/fpm/php.ini that may vary.

upload_max_filesize = 50M
post_max_size = 55M

In this case, there would be a limit of 50 MB per file.

We edit the main Nginx configuration file nginx.conf, usually found in /etc/nginx/nginx.conf, or any secondary configuration files such as vhost files, within a "Location" block, etc.

If the following directive does not exist, add it to the http block:

client_max_body_size = 50M;

Read the note at the end of this post about units of measure and PHP directives.

After making changes, it is necessary to restart Nginx and PHP-FPM.

For distributions with Systemd:

sudo systemctl restart nginx
sudo systemctl restart php7.3-fpm

For any other distribution:

sudo service nginx restart
sudo service php7.3-fpm restart

If we are using a more recent version of PHP, we change the previous command to correspond to our version, php7.*-fpm.

Notes when modifying php.ini and nginx.conf

Instead of KB, MB o GB, is simply used K, B o G, respectively; and there should be no blank spaces between the quantity and its unit of measure.

When editing php.ini, post_max_size needs to be slightly larger than upload_max_filesize for a recommendation in the official documentation.

Tags
Categories