0

There are two blocks of PHP code

Block 1

<?php
setcookie("test_cookie","0",time()-3600);
if(empty($_COOKIE["test_cookie"])){
    echo "First time browsing";
    setcookie("test_cookie","1",time()+3600);
}else{
    $count = $_COOKIE['test_cookie'];
    $count++;
    setcookie("test_cookie",$count,time()+3600);
    echo "Cookie set as " . $_COOKIE["test_cookie"] ;
}

Block 2

<?php
if(empty($_COOKIE["test_cookie"])){
    echo "First time browsing";
    setcookie("test_cookie","1",time()+3600);
}else{
    $count = $_COOKIE['test_cookie'];
    $count++;
    setcookie("test_cookie",$count,time()+3600);
    echo "Cookie set as " . $_COOKIE["test_cookie"] ;
}
    setcookie("test_cookie","0",time()-3600);

In Block 1 cookie named test is unset which should echo "first time browsing" but what i get is cookie count

In block 2 cookie named test is unset at last which echo "first time browsing" which is fine and i understand logic no matter what i set i unset at last which results in "first time browsing"

But what is wrong with with Block 1 i should have got same result as BLock 2 .. why am i getting Cookie count here ? Please do explain this in simplest way possible .

designerdarpan
  • 197
  • 1
  • 3
  • 19
  • From [documentation of `setcookie()`](http://php.net/setcookie): _"Once the cookies have been set, they can be accessed on the **next page load** with the $_COOKIE array"_ – Syscall May 10 '18 at 16:22
  • 2
    Possible duplicate of [Accessing $\_COOKIE immediately after setcookie()](https://stackoverflow.com/questions/3230133/accessing-cookie-immediately-after-setcookie) – iainn May 10 '18 at 16:22

1 Answers1

0

The setcookie function does not modify the $_COOKIE array. It just state changes, that will be sent to the client. Your changes will be available in the $_COOKIE array only on the next page loads.

If you want the $_COOKIE array to be up to date with your setcookie calls in the current request, you should updates it manually every time:

setcookie("test_cookie","0",time()-3600);
unset($_COOKIE["test_cookie"]);

setcookie("test_cookie","1",time()+3600);
$_COOKIE["test_cookie"] = "1";

Also calling setcookie after any output, as in your code, may lead to errors.

Nina Lisitsinskaya
  • 1,818
  • 11
  • 18