| only for RuBoard - do not distribute or recompile |
As projects get more complex, it can be useful to have some utility code to help you identify the cause of errors. A piece of code that you might find useful is contained in Listing 23.1. This code will echo the contents of variables passed to your page.
<?
// these lines format the output as HTML comments
// and call dump_array repeatedly
echo "\n<!-- BEGIN VARIABLE DUMP -->\n\n";
echo "<!-- BEGIN GET VARS -->\n";
echo "<!-- ".dump_array($HTTP_GET_VARS)." -->\n";
echo "<!-- BEGIN POST VARS -->\n";
echo "<!-- ".dump_array($HTTP_POST_VARS)." -->\n";
echo "<!-- BEGIN SESSION VARS -->\n";
echo "<!-- ".dump_array($HTTP_SESSION_VARS)." -->\n";
echo "<!-- BEGIN COOKIE VARS -->\n";
echo "<!-- ".dump_array($HTTP_COOKIE_VARS)." -->\n";
echo "\n<!-- END VARIABLE DUMP -->\n";
// dump_array() takes one array as a parameter
// It iterates through that array, creating a string
// to represent the array as a set
function dump_array($array)
{
if(is_array($array))
{
$size = count($array);
$string = "";
if($size)
{
$count = 0;
$string .= "{ ";
// add each element's key and value to the string
foreach($array as $var => $value)
{
$string .= "$var = $value";
if($count++ < ($size-1))
{
$string .= ", ";
}
}
$string .= " } ";
}
return $string;
}
else
{
// if it is not an array, just return it
return $array;
}
}
?>
This code will iterate through four arrays of variables that a page receives. If a page was called with GET variables, POST variables, cookies, or has session variables, these will be output.
A line of HTML will be generated for each type of variable.
The lines will resemble this:
<!-- { var1 = 'value1', var2 = 'value2', var3 = 'value3'} -->
We have put the output within an HTML comment so that it is viewable, but will not interfere with the way that the browser renders visible page elements. This is a good way to generate debugging information.
The exact output will depend on the variables passed to the page, but when added to Listing 20.4, one of the authentication examples from Chapter 20, "Using Session Control in PHP," it adds the following lines to the HTML generated by the script:
<!-- BEGIN VARIABLE DUMP -->
<!-- BEGIN GET VARS -->
<!-- -->
<!-- BEGIN POST VARS -->
<!-- { userid = testuser, password = test123 } -->
<!-- BEGIN SESSION VARS -->
<!-- { valid_user = testuser } -->
<!-- BEGIN COOKIE VARS -->
<!-- { PHPSESSID = 2552dc82bb465af56d65e9300f75fd68 } -->
<!-- END VARIABLE DUMP -->
You can see that it is displaying the POST variables sent from the login form on the previous page—userid and password. It is also showing the session variable that we are using to keep the user's name in—valid_user. As discussed in Chapter 20, PHP uses a cookie to link session variables to particular users. Our script is echoing the pseudo-random number, PHPSESSID, which is stored in that cookie to identify a particular user.
| only for RuBoard - do not distribute or recompile |