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?
It's vague. You don't really know how the data got to you since it carries post, get, and cookie data. I don't necessarily think that is always a bad thing, unless you need to know or restrict the method of delivery.
I think there is no problem with $_REQUEST
, but we must be careful when using it since it is a collection of variables from 3 sources (GPC).
I guess $_REQUEST
is still available to make old programs compatible with new php versions, but if we start new projects (including new libraries) I think we should not use $_REQUEST
anymore to make the programs clearer. We should even consider deleting uses of $_REQUEST
and replacing it with a wrapper function to make the program lighter, especially in processing large submitted text data, since $_REQUEST
contains copies of $_POST
.
// delete $_REQUEST when program execute, the program would be lighter
// when large text submitted
unset($_REQUEST);
// wrapper function to get request var
function GetRequest($key, $default = null, $source = '')
{
if ($source == 'get') {
if (isset($_GET[$key])) {
return $_GET[$key];
} else {
return $default;
}
} else if ($source == 'post') {
if (isset($_POST[$key])) {
return $_POST[$key];
} else {
return $default;
}
} else if ($source == 'cookie') {
if (isset($_COOKIE[$key])) {
return $_COOKIE[$key];
} else {
return $default;
}
} else {
// no source specified, then find in GPC
if (isset($_GET[$key])) {
return $_GET[$key];
} else if (isset($_POST[$key])) {
return $_POST[$key];
} else if (isset($_COOKIE[$key])) {
return $_COOKIE[$key];
} else {
return $default;
}
}
}
The central problem is that it contains cookies, as others have said.
In PHP 7 you can do this:
$request = array_merge($_GET ?? [], $_POST ?? []);
This avoids the cookie problem and gives you at worst an empty array and at best a merger of $_GET and $_POST with the latter taking precedence. If you are not too bothered with allowing URL injection of parameters through the query string, it's quite convenient.
The only time using $_REQUEST
is not a bad idea is with GET.
And even with GET, $_GET
is shorter to type than $_REQUEST
;)