开发者

Doubt related to PHP Cookies

I have a doubt, I will appreciate if you can clear it .

COOKIES

What are cookies? When described as entities, which is how cookies are often referenced in conversation, you can be 开发者_开发百科easily misled. Cookies are actually just an extension of the HTTP protocol. Specifically, there are two additional HTTP headers: Set-Cookie and Cookie.The operation of these cookies is best described by the following series of events:

  1. Client sends an HTTP request to server.

  2. Server sends an HTTP response with Set-Cookie: foo=bar to client.

  3. Client sends an HTTP request with Cookie: foo=bar to server.

  4. Server sends an HTTP response to client.

Thus, the typical scenario involves two complete HTTP transactions. In step 2, the server is asking the client to return a particular cookie in future requests. In step 3, if the user’s preferences are set to allow cookies, and if the cookie is valid for this particular request, the browser requests the resource again but includes the cookie.

Now my question is.......

why you cannot determine whether a user’s preferences are set to allow cookies during the first request????


The other answer is already correct, steps 3 & 4 will not occur without something to "trigger" them. When detecting whether the user has cookies enabled or not, that's usually done with a HTTP redirect, or possibly with some Javascript (if you also want to detect that they have Javascript enabled, for example).

The first request is to ask the client to set the cookie, the second request is to check that the client actually did what you asked it to do.

The reason you can't detect whether cookies are enabled without a second request is because many clients will, when they see the "Set-Cookie" header, prompt the user to see whether they want to accept it or not. So it would be impossible for the client to include a special "I accept cookies" or "I do not accept" header in the initial request, because it simply doesn't know the answer until you actually present it with a cookie.

There are many parallels with this kind of process:

  1. To check whether you have access to a file on the file system, you need to attempt to open the file.
  2. To check whether the user has Javascript turned on, you have to actually attempt to run some Javascript.
  3. To determine the compressed size of a file, you have to actually compress it.

And so on. So to check whether the user allows cookies, you have to actually try to set one.


First, a refresh does not occur unless the user specifically triggers it, so steps 3 and 4 are wrong. In any case, the browser never sends the information about whether it will accept cookies to the server. The browser makes its own decision about whether cookies are stored.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜