Start by writing the following simple code:
When accessing for the first time, error message:
The reason for the error is that the value of $_COOKIE['a'] does not exist. Second visit:
Q: Why is there no cookie when I visit for the first time? ? Shouldn't I set it first and then get it? ?
Answer: Use firefox's firebug to view "Network":
Client:
As you can see, the browser (client) sends a request to the server. When making the request, various parameters are included in the request header information to tell the server what kind of text I want to receive (Accept), What encoding format (Accept-Encoding), what language (Accept-Language), etc., of course, the cookie is also passed to the server (Cookie).
Server side:
Step one: setcookie('a','value')
Because the cookie is set on the client, the setcookie function itself cannot set the cookie. It can only tell the browser through the header information: Brother, I want to set a cookie, the key is a, the value is value, you are Could you please help me set it up? You can also understand it as: "Come, I am happy today and I will give you a cookie."
Step 2: $_COOKIE['a']$_COOKIE['a']
It’s very simple. The operation is to search for the cookie with key a in the cookie string brought by the browser and return its value.
Obviously, this cookie with "key a" cannot be found, because when the client accesses the server, this cookie does not exist at all, and the header information of the cookie set in the previous step has not yet been returned to the client. terminal (php must execute the statement from top to bottom before returning to the client)
Step 3: Server returns information
Among them, the returned header information contains "Set-Cookie a=value". The browser receives this header information and stores the cookie in a file on the computer. The storage location of the cookie seems to be different for different browsers. , this is beyond the scope of this article.
When you refresh the browser and access the server again, a lot of header information will be sent to the server, but this time there is an extra a=value in the cookie. So $_COOKIE['a'] can naturally find the value of the cookie with the key a from the cookie string.