When and why should $_REQUEST be used instead of $_GET / $_POST / $_COOKIE?

Question in the title.

And what happens when all 3 of $_GET[foo], $_POST[foo] and $_COOKIE[foo] exist? Which one of them gets included to $_REQUEST?


Solution 1:

I'd say never.

If I wanted something to be set via the various methods, I'd code for each of them to remind myself that I'd done it that way - otherwise you might end up with things being overwritten without realising.

Shouldn't it work like this:

$_GET = non destructive actions (sorting, recording actions, queries)

$_POST = destructive actions (deleting, updating)

$_COOKIE = trivial settings (stylesheet preferences etc)

$_SESSION = non trivial settings (username, logged in?, access levels)

Solution 2:

Sometimes you might want the same script to be called with several different ways. A form submit and an AJAX call comes to mind. In most cases, however, it´s better to be explicit.

Also, see http://docs.php.net/manual/en/ini.core.php#ini.request-order on how the different sources of variables overwrite each other if there is a name collision.

Solution 3:

To answer the "what happens when all 3 exist" question, the answer is "it depends."

PHP auto-fills $_REQUEST based on the request_order directive (or variables_order if request_order is absent) in PHP.INI. The default is usually "GPC" which means GET is loaded first, then POST is loaded (overwriting GET if there is a collision), then cookies are loaded (overwriting get/post if there is a collision). However, you can change this directive in the PHP.INI file. For example, changing it to "CPG" makes cookies load first, then post, then get.

As far as when to use it? I'll echo the sentiment of "Never." You already don't trust the user, so why give the user more tools? As the developer, you should know where you expect the data to come from. It's all about reducing your attack surface area.

Solution 4:

$_REQUEST is only a shortcut to prevent you from testing post, get and cooking if the data can come from any of these.

There are some pitfalls :

  • data are taken from GET, POST and finally COOKIE . The last override the first, so be careful with that.
  • REST architectures require to separate the POST and GET semantics, you can't rely on $_REQUEST in that case.

Nevertheless, if you know what you're doing, then it's just another handy PHP trick.

I'd use it if I wanted to quickly update a var that may come from several sources. E.G :

  • In your controller, to decide what page to serve without checking if the request come from a form action or a hypertext link.
  • To check if a session is still active regardless of the way session id are transmitted.