Friday, March 12, 2010

I can't upload a file larger than 8MB through a PHP script

SkyHi @ Friday, March 12, 2010
If you have php error logging with reporting set to E_ALL then you will see the PHP Error reported:

PHP Warning: POST Content-Length of 9470478 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

The problem is unset or incorrect settings in your PHP configuration file.

To allow file uploads larger than the default 8 megabytes, put these settings in your php.ini:

post_max_size = 16M
upload_max_filesize = 16M

You can check phpinfo() output to make sure that those values get set correctly.

Also make sure that your script does not have an html form input tag for MAX_FILE_SIZE that is smaller (in bytes) than the size of the files that you are trying to upload.

Now you will be able to upload files up to 16 megabytes.

NOTE: although lists post_max_size as being a PHP_INI_PERDIR, because of the way we run PHP in CGI, this cannot be changed in your .htaccess file. However, there is a workaround:

Copy your current php.ini file into the directory that you require the custom post_max_size in.

Obviously, we don't want the outside world to have access to your settings in your php.ini file. The solution? Drop an .htaccess file in the same directory with the following lines in it:

<Files ~ "^.*\.ini">
Deny From All

This will deny any web requests to any file in that directory ending in .ini; thus preventing your PHP settings from being seen by others.

Now you have a secure php.ini file that you can modify settings in to affect the .php files within that directory.