WP-Mix

A fresh mix of code snippets and tutorials

Including Arrays in URI Requests

Some esoteric code phenomena for you today.. in this post I explain how PHP handles arrays when they are included in URL requests (via the query string). It’s something I failed to grasp until doing some in-depth work developing my professional WordPress firewall plugin. Now let’s jump in..

Passing arrays via query string

When crafting a URL, you can include an array of values as query-string parameters, like so:

Literal: http://example.com/?paged=1&post[]=1179&post[]=1178
Encoded: http://example.com/?paged=1&post%5B%5D=1179&post%5B%5D=1178

So in other words, if we have the following array:

$post = array('1179', '1178');

That is equivalent to the following query-string parameter:

post[]=1179&post[]=1178

We can grab this array via PHP using $_GET['post'].

Another example, consider this simple array:

array(1, 2, 3, 4, 5)

..this would be written as:

array[]=1&array[]=2&array[]=3&array[]=4&array[]=5

And we can grab this array via PHP using $_GET['array'].

That’s basically what we’re looking at in this article. I once thought that GET requests such as these were treated by PHP as strings. How wrong I was..

Receiving arrays via query string

To understand how to receive/interpret arrays that are passed via query string, create a file named test.php and add the following code:

if (is_array($_GET['post'])) die(var_dump($_GET['post']));

After uploading the file to your server, visit your browser and request the following URI:

http://example.com/test.php?paged=1&post[]=1179&post[]=1178

The result will be something like this:

array(2) { [0]=> string(4) "1179" [1]=> string(9) "1178" }

Then repeat the test using an encoded array and the results should be the same. So the moral of the story is that you can send an array via HTTP requests, either literally or encoded. Hopefully this post sheds some light on this otherwise esoteric bit of functionality.

Incidentally, and for what it’s worth, my BBQ Pro plugin correctly parses query-string arrays (both literal and encoded) in all types of requests: GET, POST, PUT, DELETE, etc. So the bad guys ain’t sneakin’ nothin’ through via query-string arrays ;)

★ Pro Tip:

Banhammer ProBlackhole ProBBQ Pro