Using Hidden Fields to Save State

The script in Listing 9.7 has no way of knowing how many guesses a user has made, but we can use a hidden field to keep track of this. A hidden field behaves exactly the same as a text field, except that the user cannot see it unless he views the HTML source of the document that contains it. Listing 9.8 adds a hidden field to the number-guessing script and some PHP to work with it.

Listing 9.8 Saving State with a Hidden Field
  1: <?php
  2: $num_to_guess = 42;
  3: $num_tries = (isset($_POST[num_tries])) ? $num_tries + 1 : 0;
  4: $message = "";
  5: if (!isset($_POST[guess])) {
  6:      $message = "Welcome to the guessing machine!";
  7: } elseif ($_POST[guess] > $num_to_guess) {
  8:      $message = "$_POST[guess] is too big! Try a smaller number";
  9: } elseif ($_POST[guess] < $num_to_guess) {
 10:      $message = "$_POST[guess] is too small! Try a larger number";
 11: } else { // must be equivalent
 12:      $message = "Well done!";
 13: }
 14: $guess = $_POST[guess];
 15: ?>
 16: <html>
 17: <head>
 18: <title>Listing 9.8 Saving state with a hidden field</title>
 19: </head>
 20: <body>
 21: <h1>
 22: <?php print $message ?>
 23: </h1>
 24: Guess number: <?php print $num_tries?>
 25: <form action="<?php print $_SERVER[PHP_SELF] ?>" method="POST">
 26: Type your guess here:
 27: <input type="text" name="guess" value="<?php print $guess?>">
 28: <input type="hidden" name="num_tries" value="<?php print $num_tries?>">
 29: </form>
 30: </body>
 31: </html>

The hidden field on line 28 is given the name "num_tries". We also use PHP to write its value. While we're at it, we do the same for the "guess" field on line 27 so that the user can always see his last guess. This technique is useful for scripts that parse user input. If we reject a form submission for some reason, we can at least allow our user to edit his previous query.

Within the main PHP code, we use a ternary operator to increment the $num_tries variable. If the $num_tries variable is set, we add one to it and reassign this incremented value; otherwise, we initialize $num_tries to 0. Within the body of the HTML, we can now report to the user how many guesses he's made.

Put these lines into a text file called listing9.8.php, and place that file in your Web server document root. Access the form a few times with your Web browser, and try to guess the number (pretend you don't already know it).

    Part III: Getting Involved with the Code