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?
PHP $_REQUEST is a PHP super global variable which is used to collect data after submitting an HTML form. The example below shows a form with an input field and a submit button. When a user submits the data by clicking on "Submit", the form data is sent to the file specified in the action attribute of the <form> tag.
The $_REQUEST variable is used to read the data from the submitted HTML form. Sample code: Here, the $_REQUEST variable is used to read the submitted form field with the name 'username'. If the form is submitted without any value, then it will print as “Name is empty”, otherwise it will print the submitted value.
$_POST : It can catch the data which is sent using POST method. $_GET : It can catch the data which is sent using GET method. $_REQUEST : It can catch the data which is sent using both POST & GET methods.
PHP's $_REQUEST is widely used to collect information that is after submitting from HTML browsed forms. The $_REQUEST function is used to get the form information sent with its POST method and the other GET method.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With