PHP Cookies
2003-06-22 14:19:41
Category: php:cgi
Description: Example on storing cookies in the client's browser, and controlling the expire time on the server instead of the client.
Author: detour
Viewed: 12504
Rating: (52 votes)


<?php
/* cookie.php by detour@metalshell.com
 *
 * Example on storing cookies in the client's browser.
 * You will notice that I do not let the browser determine
 * when the cookie will expire, the reason for doing this
 * is becuase often clocks are wrong on either the clients machine
 * or sometimes the server.  By setting a cookie value with the
 * local server time and then comparing it each time the cookie
 * is read will avoid this, allowing the expire time to be much
 * more accurate.
 *
 * http://www.metalshell.com/
 *
 */
 
 
// Expire in 60 seconds
$expire_time = 60;
 
if($_COOKIE["mycookie"]) {
  // Convert the string back into an array.
  $cook = unserialize(stripslashes($_COOKIE["mycookie"]));
 
  // Print out each value.
  foreach($cook as $key => $value)
    print "$key: $value<br>";
 
  /* Compare the time the cookie was set with the current time, and
     if it has expired tell the client it expired a week ago so that
     it can erase it. */
  if(time() - $cook["expire"] >= $expire_time) {
    print "<h3>Cookie set to expire.</h3>";
    setcookie("mycookie", "clearing", time()-60*60*24*7);
  }
 
  // Seconds left till the cookie expires.
  print "Seconds left: " . ($expire_time - (time() - $cook["expire"])) . "<br>";
 
} else {
  print "Setting cookie.";
 
  // Build an array to store on the clients browser.
  $cookieset["fish"] = "trout";
  $cookieset["dog"] = "hound";
  $cookieset["cat"] = "cheetah";
  $cookieset["expire"] = time();
 
  /* Serialize will turn an array into a string so that it can later be turned
     back into an array by using unserialize.  The serialize output is something
     like:
       a:4:{s:4:"fish";s:5:"trout";s:3:"dog";s:5:"hound";s:3:"cat";...}
 
     This is very handy because it allows you to store multiple values in one,
     cookie making things a little cleaner. */
 
  /* Set the cookie to expire in one week, you would need to raise this if you
     set $expire_time to greater then a week. */
  setcookie("mycookie", addslashes(serialize($cookieset)), time()+60*60*24*7);
}
 
 
?>