2

Though I have set the cookie using setcookie, why does it skip to the else part during the first time of execution/ first visit?

<?php
    setcookie("dan", "Sony", time()+60);
    if(isset($_COOKIE['dan']))
    {
        echo "Set";
    }
    else
    {
        echo "Not yet!";
    }

?>

P.S: I know it is a naive question and gets downvoted but I don't find a better forum than StackOverflow.

Daniel_V
  • 174
  • 1
  • 2
  • 16

3 Answers3

1

setcookie() merely arranges for the HTML headers emitted by the PHP script to contain the necessary "Set-Cookie:" header. The browser responds by storing the cookie and then regurgitating it on the next request to the site.

setcookie() does not set any variables inside the currently-executing script, which is why you're not seeing anything the first time through.

cvkline
  • 415
  • 5
  • 7
0

You can't get value from $_COOKIE in the same request you do setcookie, you could get it begin from the next request.

The first time you only tell the browser to set the cookie, at the time, there is no cookie data in the request header (which could get from $_COOKIE).

xdazz
  • 158,678
  • 38
  • 247
  • 274
  • How do i "tell the server" to send me a cookie via the header Set-Cookie for the first time? i am struggling with it, – Jonathan1609 Jul 18 '21 at 23:19
0

Set your cookies with javascript.

 function createCookie(name,days,value) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        } else var expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
    }

    function readCookie(name) { //cookie reader function
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    }

    function eraseCookie(name) { //cookie eraser function
        createCookie(name,"",-1);
    }
            createCookie("test", 1, 1);
            var mycookie= readCookie("test");
            alert(mycookie);