Accessing All the Fields from a Form in an Associative Array in PHP

Leave a Comment

The techniques you have looked at so far work well, as long as your script knows in advance what fields to expect. You may often want to write code that can adapt to changes in a form or even service more than one form, without worrying itself about the names of specific form fields.

The global variables that PHP4 makes available provide the solution to this problem. According to whether or not a submitting form used the GET or POST method, you will have access to one or both of $HTTP_GET_VARS or $HTTP_POST_VARS. These are associative arrays that contain the name/value pairs submitted. Below code takes advantage of this to list all the fields submitted from a form via a GET request.
<html>
<head>
<title>Listing 9.6 Reading input from any form using the $HTTP_GET_VARS array</title>
</head>
<body>
<?php
foreach ( $HTTP_GET_VARS as $key=>$value )
{
print "$key == $value<BR>\n";
}
?>
</body>
</html>

This code lists the names and values of all parameters passed to it via a GET transaction. Of course, it's not yet smart enough to deal with parameters that have been set up to resolve to arrays.
<html>
<head>
<title>Listing 9.7 Reading input from any form using the $HTTP_GET_VARS array</title>
</head>
<body>
<?php
foreach ( $HTTP_GET_VARS as $key=>$value )
{
if ( gettype( $value ) == "array" )
{
print "$key == <br>\n";
foreach ( $value as $two_dim_value )
print ".........$two_dim_value<br>";
}
else
{
print "$key == $value<br>\n";
}
}
?>
</body>
</html>

As before, we use foreach to loop through the $HTTP_GET_VARS array. We use the gettype() function to ascertain whether each of its values is an array. If the value is itself an array, we create a second foreach statement to loop through it, outputting each value to the browser.

0 comments:

Post a Comment