Home > Articles > Programming > PHP

  • Print
  • + Share This
This chapter is from the book

Distinguishing Between GET and POST Transactions

To work flexibly, a script that can accept data from any source must be able to decide whether to read the $HTTP_GET_VARS or $HTTP_POST_VARS arrays. On most systems, you can discover whether you are dealing with a GET or POST transaction in the predefined variable $REQUEST_METHOD, which should contain the string "post" or "get". To be absolutely sure that your scripts are entirely portable, however, you can simply test both arrays for elements.

Listing 9.7 amends our form parser script to work with the correct array every time.

Listing 9.7 Extracting Parameters from Either a GET or POST Request

 1: <html>
 2: <head>
 3: <title>Listing 9.7 Extracting parameters from
 4:    either a GET or POST request</title>
 5: </head>
 6: <body>
 7: <?php
 8: $PARAMS = ( count( $HTTP_POST_VARS ) )
 9:     ? $HTTP_POST_VARS : $HTTP_GET_VARS;
10:   
11: foreach ( $PARAMS as $key=>$value ) {
12:  print "$key == $value<BR>\n";
13: }
14: 
15: ?>
16: </body>
17: </html> 

We use the ternary operator on line 8 to set a variable called $PARAMS. Using the built-in count() function, we first check whether the $HTTP_POST_VARS array contains elements. If the $HTTP_POST_VARS array is not empty, the ternary expression resolves to this; otherwise, it resolves to $HTTP_GET_VARS. We can now use the $PARAMS array throughout the rest of the script without worrying about whether it has been populated as the result of a GET or a POST request.

  • + Share This
  • 🔖 Save To Your Account