Understanding Cookies in PHP

前端 未结 4 554
鱼传尺愫
鱼传尺愫 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 07:54

    When calling setcookie, PHP sets an HTTP Cookie header that's delivered to the client together with the rest of the output of the script. The client (browser) will then store this cookie in its cookie storage and send it back to the server on subsequent requests.

    $_COOKIE contains all the cookies that have been received in the current request from the client. The first time that's nothing, since the client hasn't received the Cookie header yet. Only on subsequent requests does the client send the cookie which gets stored in $_COOKIE. setcookie() does not populate the $_COOKIE variable.

          Client       Server
    
    1.            -->  $_COOKIE is empty
    
    2.           Cookie
          store   <--  setcookie()
    
    3.           Cookie
           send   -->  $_COOKIE is set
    

提交回复
热议问题