lesterpierson123
lesterpierson123

Reputation: 165

Cookie value not incrementing in PHP

For some reason I'm trying to have my "else" statement increment the amount of times the person has been to my website and it's not incrementing correctly. When I run my php, all it does it increment it once, after that, there are no more refreshes and the $cookieValue just keep echoing 2 instead of 3,4,5,6... What am I missing here?

<?php
  date_default_timezone_set('EST');
  if (!isset($_COOKIE["time"])) {
    $cookieValue = 1;
    setcookie("time", $cookieValue, time()+(86400*365));
  }

  $cookieLastVisit = date(DATE_RFC1036);
  setcookie("lastVisit", $cookieLastVisit, time()+(86400*365));
?>
<html>
  <head>
    <title>Question 2</title>
  </head>
  <body>
    <?php
      if ($cookieValue == 1){
        echo ("Welcome to my webpage! It is the first time that you are here.");
      } else {

        $cookieValue = ++$_COOKIE["time"];

        echo("Hello, this is the " . $_COOKIE["time"]  . " time that you are visiting my webpage. Last time you visited my webpage on: " . $cookieLastVisit . " EST");

        $visit = date(DATE_RFC1036);
        setcookie("lastVisit", $visit);
      }
    ?>
  </body>
</html>

Upvotes: 1

Views: 281

Answers (2)

WEBjuju
WEBjuju

Reputation: 6581

Move the setting of the cookie time var to the same place as the declaration.

<?php
  date_default_timezone_set('EST');
  if (!isset($_COOKIE["time"])) {
    $cookieValue = 1;
  } else {
    $cookieValue = ++$_COOKIE["time"];
  }
  setcookie("time", $cookieValue, time()+(86400*365));

  $cookieLastVisit = date(DATE_RFC1036);
  setcookie("lastVisit", $cookieLastVisit, time()+(86400*365));
?>
<html>
  <head>
    <title>Question 2</title>
  </head>
  <body>
    <?php
      if ($cookieValue == 1){
        echo ("Welcome to my webpage! It is the first time that you are here.");
      } else {

        echo("Hello, this is the " . $_COOKIE["time"]  . " time that you are visiting my webpage. Last time you visited my webpage on: " . $cookieLastVisit . " EST");

        // you can't set cookie after you've output to the browser :/
        //$visit = date(DATE_RFC1036);
        //setcookie("lastVisit", $visit);
      }
    ?>
  </body>
</html>

Upvotes: 1

Dekel
Dekel

Reputation: 62566

You need to set the value of the cookie. The change to the $_COOKIE variable doesn't save the value of the cookie in "the next" page

else {
    $cookieValue = ++$_COOKIE["time"];
    setcookie("time", $cookieValue, time()+(86400*365));
    ...
} 

Upvotes: 1

Related Questions