Arrays In PHP $_POST / $_GET Values

HTTP requests can of course be spoofed, just because your form says data should be transferred using GET or POST with specified names for element keys, this does not mean someone can’t alter the form before submission or even just use a cURL client or something similar to simply create the request however they like. This is a given and good white list filtering / validation is the norm for this very reason, one thing ‘they’ could do is replace scalar values with arrays as simply as adding square brackets after an input name.

This does not generally cause direct security risks to PHP scripts (assuming you are filtering your input and escaping your output) however due to the nature of most filtering and related functions which expect a scalar, being passed an array will cause errors, something I had not really considered working around before, however the issue came up with some recent vulnerability testing at work.

I don’t like errors to occur (and therefore get reported) unless something is truly ‘wrong’, therefore it makes sense to accommodate for dirty arrays being passed to my scripts where not expected.

Iterative type checks on the super global arrays can be put in place to check for arrays being present but you may actually want arrays to be allowed through if this was your original intention, or as in my case you may want a simple refactor to fix the issue in place.

As it turns out, casting an array to an integer will result in 0 or 1 depending if the array has any elements:

And if we cast to a string we simply get the string ‘Array’:

Strange no? – So to avoid the arrays causing issues I’ve ended up with casting values (string) or (int) prior to initial trim/stripslashing/strip_tags to ensure they are indeed scalar, and then add a simple tenary check for the string casted values:

The following validation will then pickup on the empty string and cause a natural fail (rather than cause errors). The same applies for 0 and 1 if they are illegal values, but in many cases 1 can simply be allowed through as a kind of default (e.g. a postId style GET variable).

About Ingmar Boddington

Codemonkey, Sheffield, UK
This entry was posted in PHP and tagged forms, PHP, Security, Validation. Bookmark the permalink.