A quick PHP function to get Post, Get, or Session variables; and Cookies too
It should be pretty easy to get $_GET, $_POST, $_SESSION, or $_COOKIE variables in PHP code. The problem is that just entering $_GET['variable'] causes an error if the variable does not exist. What's needed is a way to open the variable, and get a blank string if the variable is not defined.
That's what this function does. You pass a variable name and it searches through the get, post, session, and cookie arrays to see if it exists. If the variable doesn't exist in any of these arrays, a blank string is returned. More importantly, no error is tripped.
It checks in the order get, post, session, and cookie. So, if you have a cookie and a session variable named 'something', the value in $_SESSION['something'] will be returned.
-
function getvar($sVarName)
-
/* Returns the value of a passed variable either by GET or
-
POST. Will return a blank string if the variable does not
-
exist in either method.
-
Notes: This function will check to see if the variable
-
exists in the GET collection first. If it does
-
not then it will check the POST. If the variable
-
does not exist in either it will return a blank
-
string. Failing those two, it will check SESSION
-
variables and then cookies.
-
*/
-
{
-
{
-
$temp = $_GET[$sVarName];
-
}
-
{
-
$temp = $_POST[$sVarName];
-
}
-
{
-
$temp = $_SESSION[$sVarName];
-
}
-
{
-
$temp = $_COOKIE[$sVarName];
-
}
-
else
-
{
-
$temp = "";
-
}
-
-
//Return variable to calling routine
-
return $temp;
-
}




Daniel on June 16th, 2008 at 12:34 pm
There are a few things wrong with this code. Line 28, instead of looking in $_COOKIE, attempts to call a function $_SESSION. (And $_SESSION is, of course, actually an array rather than a function.) And no check is made as to whether there is a session, which could result in a failure at line 22.