Page 160 - Open Soource Technologies 304.indd
P. 160

Unit 9: Working with Forms



              13.  }                                                                              Notes
              14.  $guess = $_POST[guess];

              15.  ?>
              16.  <html>

              17.  <head>
              18.  <title>Listing 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.
                          Be sure that absolutely no output has been sent to the browser. The first time
                          content is sent to the browser, PHP sends out headers and it’s too late for
                          you to send your own. Any output from your document, even a line break
                          or a space outside of your script tags, causes headers to be sent. If you intend
                          to use the header() function in a script, you must make certain that nothing
                          precedes the PHP code that contains the function call. You should also check
                          any libraries that you might be using.

            Listing 9 shows typical headers sent to the browser by PHP, beginning with line 3, in response
            to the request in line.

            9.6 Redirecting the User


            Our simple script still has one major drawback. The form is rewritten whether or not the user
            guesses correctly. The fact that the HTML is hard-coded makes it difficult to avoid writing the
            entire page. We can, however, redirect the user to a congratulations page, thereby sidestepping



                                             LOVELY PROFESSIONAL UNIVERSITY                                   155
   155   156   157   158   159   160   161   162   163   164   165