Cookie值不会在PHP中递增

时间:2016-12-06 02:12:25

标签: php html cookies

出于某种原因,我试图让我的“其他”语句增加该人访问我的网站的次数并且它没有正确递增。当我运行我的PHP时,所有它都会增加它一次,之后,没有更多的刷新和$ cookieValue只是保持回响2而不是3,4,5,6 ...我在这里缺少什么?

<?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>

2 个答案:

答案 0 :(得分:1)

您需要设置Cookie的值。对$_COOKIE变量的更改不会将cookie的值保存在“下一页”

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

答案 1 :(得分:1)

将cookie time var的设置移动到与声明相同的位置。

<?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>