2016-12-06 120 views
1

出於某種原因,我試圖讓我的「其他」語句增加該人訪問我的網站的次數,並且它沒有正確遞增。當我運行我的PHP,所有它會增加一次,之後,沒有更多的刷新和$ cookieValue只是保持呼應2,而不是3,4,5,6 ...我在這裏錯過了什麼?Cookie值不會在PHP中增加

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

怎麼值成爲2時'$ cookieValue = ++ $ _ COOKIE [ 「時間」];'如果'$ cookieValue'不等於1,但條件'$ cookieValue僅適用== 1'裏面沒有增量代碼? –

+0

@MarkVincentManjac你是對的......我其實不知道。它在刷新頁面時跳轉到else語句。 – lesterpierson123

+0

無論如何,只要按照Dekel的答案。有用。 –

回答

1

請將Cookie時間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> 
1

您需要設置cookie的值。到$_COOKIE變量的變化不保存cookie的值在「下一個」頁面

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

它不起作用,在我不斷地重新加載頁面之後,它仍然在我的其他回聲中輸出2。 – lesterpierson123