Understanding Cookies in PHP

前端 未结 4 561
鱼传尺愫
鱼传尺愫 2021-01-01 07:39

When the following code is run for the first time, it does not echo out the \"var1\" value but it does on browser refresh (f5), Why? As i understand when the browser sends t

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-01 08:02

    It's all explained in the manual. setcookie() causes a Set-Cookie: response header to be returned to the browser. The $_COOKIE array can only be filled with the next HTTP refresh when the browser had the opportunity to reply back with the Cookie: request header.

    When the following code is run for the first time, it does not echo out the "var1" value but it does on browser refresh (f5), Why?

    The browser needs to send the cookie back. On the first request it doesn't know about that cookie yet. After the refresh it does. Only then it can send it.

    As i understand when the browser sends the code to the server,

    On the second request.

    setcookie() stores the cookie variable ("var1") to a client (browser) in a local file

    The browser saves it.

    and puts the "var1" value available in global domain via $_COOKIE superglobal.

    Not immediately.

    Since "var1" value is available immediately in $_COOKIE after the first server replies to browser's initial request, then why the "var1" is not echoed out.

    It is not immediately in $_COOKIE. It can't be. That array is only populated once, when PHP starts.

    Is it that setcookie() stores "var1" value in client's browser on first request and only when the page is refreshed (2nd request) the browser sends back "var1" value to the server and then the server makes it available in the global domain via $_COOKIE function.

    Yes. That's how it works.

提交回复
热议问题