DJ Mike's Tutorials: PHP

Cookies pt.2


< ^ >

Demo

<?
$rand 
rand(0,1000);
$location "http://$_SERVER[HTTP_HOST]$_SERVER[PHP_SELF]?$rand";
if ( isset(
$_POST[name]) || isset($_POST[pass]) )
{
  
setcookie("tutorial_name""$_POST[name]"time()+60*60 ); 
  
setcookie("tutorial_pass""$_POST[pass]"time()+60*60); 
  
header("location:$location");
}

if ( isset(
$_GET[delete]) )
{
  
setcookie("tutorial_name"""time()-60 );
  
setcookie("tutorial_pass"""time()-60 );
  
header("location:$location");
}
?>
<html>
<body>

<form method="post" action="<?php echo $_SERVER[PHP_SELF]; ?>">
Name <input type="text" name="name" value="<? echo $_COOKIE[tutorial_name]; ?>" /><br />
Pass <input type="text" name="pass"  value="<? echo $_COOKIE[tutorial_pass]; ?>" /><br />
<input type="submit" value="Set Cookies" /><br />
</form>
<form>
<input type="submit" name="delete" value="Delete Cookies"/>
</form>

Name
Pass

In the previous page, I showed that since the server sends the cookie to the prowser at the same time that it sends the web page, the cookie is not accessible to the server until the browser makes another request for the page along with the cookie. Now I am going to show you a trick to make the cookie available to the server without the user having to reload the page.

Although the cookie is not immediately to the page that sets it, if you use a second header to change the location, the cookie will be available the second page. The browser requests the first page, the server sends it with then redirects the server. The browser, now having a cookie sends it to the server along with a request for te second page. The server creates the second web page incorporating the information in the cookie and sends it to the server. The trick is to resend the first page to the browser a send time, tricking the browser into thinking it is a new page.

Whenever you append something to the URL as a get request, the browser makes a new HTTP request. in other words, math_functions.php and math_functions.php#rand is treated as if they were different pages even though they are really the same the same. To pull off this trick, I first create a random number with rand(). Instead of hard coding the destination URL I construct it from elements from the $_SERVER array and my random number, $rand, like so:

<?
http
://www.eclecticdjs.com/mike/tutorials/php/cookies_02.php?50 = "http://$_SERVER[HTTP_HOST]$_SERVER[PHP_SELF]?$rand";
?>


This modified URL is used in the location header

header("location:$location");


< ^ >


Created by DJ Mike from Santa Barbara

DJ Mike


Dance Away Santa Barbara's Home Page
<a href="http://www.statcounter.com/" target="_blank"> <img src="http://c5.statcounter.com/counter.php?sc_project=1321035&java=0&security=da2193dc" alt="counter free hit invisible" border="0" /></a>