Page 319 - Beginning PHP 5.3
P. 319
Chapter 10: Preserving State With Query Strings
The forgetInfo() function sets both the firstName and location cookies ’ expiry times to one hour
ago, effectively deleting them from the browser. It then sends a Location: header to reload the remember_
me.php script. The browser won ’ t send the cookies to the script because they ’ ve just been deleted:
function forgetInfo() {
setcookie( “firstName”, “”, time() - 3600, “”, “”, false, true );
setcookie( “location”, “”, time() - 3600, “”, “”, false, true );
header( “Location: remember_me.php” );
}
The final function, displayPage() , displays the output to the visitor. It starts by creating two
variables to hold the values from the user info cookies (if any):
$firstName = ( isset( $_COOKIE[“firstName”] ) ) ? $_COOKIE[“firstName”] : “”;
$location = ( isset( $_COOKIE[“location”] ) ) ? $_COOKIE[“location”] : “”;
Next, after displaying the page header, the function looks at the values of $firstName and
$location . If either variable contains a non - empty value, the function displays a greeting page,
including the visitor info, a short nursery rhyme, and the “ Forget about me! ” link that links back to the
remember_me.php script. This link contains a query string, action=forget , to signal to the script
that the user wants to delete her information:
< ?php if ( $firstName or $location ) { ? >
< p > Hi, < ?php echo $firstName ? $firstName : “visitor” ? > < ?php echo
$location ? “ in $location” : “” ? > ! < /p >
< p > Here’s a little nursery rhyme I know: < /p >
< p > < em > Hey diddle diddle, < br / >
The cat played the fiddle, < br / >
The cow jumped over the moon. < br / >
The little dog laughed to see such sport, < br / >
And the dish ran away with the spoon. < /em > < /p >
< p > < a href=”remember_me.php?action=forget” > Forget about me! < /a > < /p >
However, if both $firstName and $location are empty, the script instead displays the user info form:
< ?php } else { ? >
< form action=”remember_me.php” method=”post” >
< div style=”width: 30em;” >
< label for=”firstName” > What’s your first name? < /label >
< input type=”text” name=”firstName” id=”firstName” value=”” / >
< label for=”location” > Where do you live? < /label >
< input type=”text” name=”location” id=”location” value=”” / >
< div style=”clear: both;” >
< input type=”submit” name=”sendInfo” value=”Send Info” / >
< /div >
< /div >
< /form >
< ?php } ? >
281
9/21/09 9:05:12 AM
c10.indd 281
c10.indd 281 9/21/09 9:05:12 AM