Jump to content

Cookie and Session Problem


atl_andy

Recommended Posts

I'm taking an online PHP class and the topic is cookies and sessions.  They have there own editor that runs in my browser.  There is a simple script that I found to experiment with cookies.  The script will work in their editor just fine, but will not work on either of my laptops.  One is running Fedora 8, the other OS X Leopard.  Is there any reason this simple piece of code will not work on my laptops?  Cookie are enabled, and I can see it stored in the broswer (FF 2.0 and Safari).  Is there a setting in php.ini that should be changed?  This seems so simple but I can't figure it out.

 

I found the script online from an O'Reilly book located here: http://www.oreilly.com/catalog/webdbapps/chapter/ch08.html

 

<?php

// See if the HTTP request has set $count as the result of a Cookie called "count"
if(!isset($count)) {
   $count = 0;

   // .. and set a cookie with the "start" time of this stateful interaction
   $start = time();
   setcookie("start", $start, time() +100, "/", "", 0);

} else {
   $count++;
}

// Set a cookie "count" with the current value
setcookie("count", $count, time() +100, "/", "", 0);

?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>Cookie</title></head>
<body>
  <p>The cookie is:</p>
  <br>count = <? echo $count ?>.
  <br>start = <? echo $start ?>.
  <p>This session has lasted
    <?php
      $duration = time() - $start;
      echo $duration;
    ?>
  seconds.
</body>
</html>

Link to comment
https://forums.phpfreaks.com/topic/100810-cookie-and-session-problem/
Share on other sites

The code is dependent on register globals being on (the program variable $count is magically populated from the cookie of the same name.)

 

Register globals were turned off by default in php 4.2 in the year 2002 because they were a huge security hole. No new code, books, tutorials... should have been written after that point in time that relied on register globals being on.

 

To make your existing code work, you need to add the following before the first reference to $count -

 

$count = $_COOKIE['count'];

 

Edit: Or better yet, change the if(!isset...) statement to the following -

 

if(!isset($_COOKIE['count'])) {

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.