green php elephants - elephpantsI came across an interesting problem the other day when a fairly large (poorly written) form seemingly wasn’t being completely processed, and no one could figure out exactly why. Now we’re all familiar with the post_max_size PHP configuration option which controls the maximum size of a form POST, and usually this is the first one that gets turned to when it appears as if a POST isn’t coming through correctly.

However, in this particular case it was only small strings being pushed through, meaning that size wasn’t an issue here – so I did a little digging and found this little bugger: max_input_vars.

It turns out that by default, PHP applied a 1000 element limit to the $_POST variable. If the limit was exceeded, then PHP would simply truncate the $_POST variable back to the correct size – which was exactly what was happening with the large form in our case.

Luckily for us, with version 5.3.9 of PHP came this new configuration option, max_input_vars, which allows us to change this limit. From the documentation:

max_input_vars: How many input variables may be accepted (limit is applied to $_GET, $_POST and $_COOKIE superglobal separately). Use of this directive mitigates the possibility of denial of service attacks which use hash collisions. If there are more input variables than specified by this directive, an E_WARNING is issued, and further input variables are truncated from the request. This limit applies only to each nesting level of a multi-dimensional input array.

Note that you can’t set this configuration option at runtime meaning that you must add it to your php.ini file and reload the Apache server.

If you are working in Ubuntu from a terminal:

# add your new value anywhere in the php.ini file: max_input_vars = 2000
sudo nano /etc/php5/apache2/php.ini
# reload apache
sudo service apache2 reload