I came upon someone's ancient 'blog entry in which he or she attempted to present what would be a useful PHP function. Unfortunately, the code has a few bugs.
A dynamic webpage may seek data from various sources, including data passed by
POST methods (which is how web forms normally), persistent data in cookies (stored on the client but provided to the server with each visit), and persistent data on the server.
Towards that end, PHP maintains five associative arrays:
The 'blog entry in question
$_REQUEST combines the contents of
$_COOKIE.) To access a variable named
POST method, one would refer to
$_POST["user"], and so forth.
may have been written before
was introduced; in any event, the author had two good ideas:
- Avoid errors resulting from trying to access variables that don't actually exist. If no variable
user was passed by
$_POST["user"] throws an error. To avoid that sort of thing, the author checks for the presence of the variable before attempting to access it.
- Combine the variables in
$_SESSION, as well as those in
$_COOKIE. Indeed, session data is more analogous to cookie data than is cookie data to data transmitted by
$_GET or by
The problems with the actual code
- If the server is not maintaining session data, then the attempt to use
$_SESSION will itself cause an error.
- There is an attempt to get cookie data from the array
- In the aforementioned attempt, the array is treated as a function.
Here's a version of the code that fixes those problems:
if (array_key_exists($var_name, $_GET) == TRUE) $ret_value = $_GET[$var_name];
else if (array_key_exists($var_name, $_POST) == TRUE) $ret_value = $_POST[$var_name];
else if (session_id() != "")
if (array_key_exists($var_name, $_SESSION) == TRUE) $ret_value = $_SESSION[$var_name];
else if (array_key_exists($var_name, $_COOKIE) == TRUE) $ret_value = $_COOKIE[$var_name];
else $ret_value = "";
also provides analogous associative arrays for other global variables
, but what unites the variable types of the five here is that they are commonly used in session-tracking — keeping data associated with a specific visitor as she moves through one's site. Possibly,
would be better named something else, if not distinguished by being made a member of some class of objects.