Monday, June 11, 2012

What"s wrong with using $_REQUEST[]?

I've seen a number of posts on here saying not to use the $_REQUEST variable. I usually don't, but sometimes it's convenient. What's wrong with it?

Source: Tips4all

1 comment:

  1. There's absolutely nothing wrong with taking input from both $_GET and $_POST in a combined way. In fact that's what you almost always want to do:

    for a plain idempotent request usually submitted via GET, there's the possibility the amount of data you want won't fit in a URL so it has be mutated to a POST request instead as a practical matter.
    for a request that has a real effect, you have to check that it's submitted by the POST method. But the way to do that is to check $_SERVER['REQUEST_METHOD'] explicitly, not rely on $_POST being empty for a GET. And anyway if the method is POST, you still might want to take some query parameters out of the URL.

    No, the problem with $_REQUEST is nothing to do with conflating GET and POST parameters. It's that it also, by default, includes $_COOKIE. And cookies really aren't like form submission parameters at all: you almost never want to treat them as the same thing.

    If you accidentally get a cookie set on your site with the same name as one of your form parameters, then the forms that rely on that parameter will mysteriously stop working properly due to cookie values overriding the expected parameters. This is very easy to do if you have multiple apps on the same site, and can be very hard to debug when you have just a couple of users with old cookies you don't use any more hanging around and breaking the forms in ways no-one else can reproduce.

    You can change this behaviour to the much more sensible GP (no C) order with the request_order config in PHP 5.3. Where this is not possible, I personally would avoid $_REQUEST and, if I needed a combined GET+POST array, create it manually.