Our simple script still has one major drawbackthe form is reloaded 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 the issue altogether.
When a server script communicates with a client, it must first send some headers that provide information about the document to follow. PHP usually handles this for you automatically, but you can choose to send your own header lines with PHP's header() function.
To call the header() function, you must be absolutely sure that no output has been sent to the browser. The first time content is sent to the browser, PHP sends out headers of its own, and it's too late for you to send any more. Any output from your document, even a line break or a space outside 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 11.8 shows typical headers sent to the browser by PHP, beginning with line 3, in response to the request in line 1.
Listing 11.8. Typical Server Headers Sent from a PHP Script
By sending a Location header instead of PHP's default header, you can cause the browser to be redirected to a new page, such as
Assuming that we've created a suitably upbeat page called congrats.html, we can amend our number-guessing script to redirect the user if she guesses correctly, as shown in Listing 11.9. The only change between this and Listing 11.7 comes after the else clause on line 10.
Listing 11.9. Using header() to Redirect User
The else clause of our if statement on line 10 now causes the browser to send us away to a page called congrats.html. We ensure that all output from the current page is aborted with the exit statement on line 12, which immediately ends execution and output of this script.