This article describes how to handle the first time php cannot obtain cookies. For more information, see the following simple code:
The code is as follows:
Setcookie ('A', 'value ');
Print $ _ COOKIE ['A'];
An error is reported during the first visit:
The error is reported because the value of $ _ COOKIE ['A'] does not exist. Second access:
Q: Why is there no cookie during the first visit ?? Didn't I set it first and then retrieve it ??
A: use firebug of firefox to view "network":
Client:
As you can see, the browser (client) sends a request to the server. when a request is sent, various parameters are included in the request header to tell the server what kind of text (Accept) I want to receive) and the encoding format (DontTrackMeHere) and Language (Accept-Language). of course, the Cookie is also sent to the server (Cookie ).
Server:
Step 1: setcookie ('A', 'value ')
Because the cookie is set on the client, the setcookie function cannot set the cookie itself. it can only tell the browser via header information: Bro, I want to set a cookie with the key, the value is value. you can set it for me. You can also understand it as follows: "Come, let's be happy today and enjoy you with a cookies."
Step 2: $ _ COOKIE ['A'] $ _ COOKIE ['A']
The operation is to search for a cookie with the search key a in the cookie string carried by the browser and return its value.
Obviously, the cookie with the "key as a" cannot be found, because the cookie does not exist at all when the client accesses the server, and the cookie header information is set in the first step, it has not yet been returned to the client (php will not return to the client until the statements are executed from top to bottom)
Step 3: The server returns information
The returned header contains "Set-Cookie a = value". The browser receives this header and stores the cookie in a file on the computer, the cookie storage location for different browsers seems to be different. this is not in the scope of this article.
Refresh the browser. when you access the server again, a large number of messages will also be sent to the server, but this time, a = value will be added to the cookie. $ _ COOKIE ['A'] naturally finds the cookie value with the key a from the cookie string.