Wednesday, May 6, 2009

When to use $_REQUEST in PHP?


We know that php is having Super Global variables such as $_GET, $_POST, $_COOKIE, $_SESSION, $_SERVER, $_ENV, $_FILES and $_REQUEST.

Here $_GET is used for collecting data passed thro' querystring parameter in the url.
Form posted using get method will pass the values as querystring parameters.

Consider below url,

www.qualitypointtech.com/showprofile.php?userid=10

If we want to receive the userid, we need to use below statement in showprofile.php.

$userid=$_GET['userid'];

Consider below form,

<form name="frmprofile" action="showprofile.php" method="post">

<input name="userid" type="hidden" value="10">


</form>

In this case, if we want to receive the userid, we need to use below statement in showprofile.php.

$userid=$_POST['userid'];

Assume below scenario,

-We may get userid as querystring in url.
-We may get userid in the form using post method.


In this case, we are unsure about which one we need to use. $_GET or $_POST?

$_REQUEST will be useful in this case. In these situation, we can get userid as below,

$userid=$_REQUEST['userid'];

i-e $_REQUEST will have variables of both $_GET and $_POST.

We need to be very careful when using $_REQUEST. Because, in addition to $_GET and $_POST, it will have variables of $_COOKIE also.

We can assume $_REQUEST as an array which is clone of $_GET overwritten with $_POST which is further overwritten with $_COOKIE.

So, if $_COOKIE is set with userid in any of the page, then $_REQUEST will have this cookie value only.

i-e if $_COOKIE['userid']=11, then $_REQUEST will return 11 only even when userid is passed as 10 in the url.

And also, since $_REQUEST includes cookies it will lead to security issues.

So it is good if we design our pages/flow so as to avoid use of $_REQUEST.


More Articles...

No comments:

Search This Blog