开发者

Problem with cookies detection in PHP

Here is the simple function that I'm using:

public function control() {
    $string = 'lolcheck';

    setcookie($string, $string, time() + 120, $this->path, $this->domain);

    if (isset($_COOKIE[ $string ])) return true;
    else return false;
}
开发者_运维问答

The problem is that it only works when I open the page twice, because it gets the previously set cookie.

Apparently everyone suggest to use this practice, but its not working for me.

Am I missing something?


Cookies do not work that way. When a cookie is set, it is not available (i.e. a corresponding $_COOKIE key exists) until the next request.

What actually happens is:

  • client sends a requests
  • server sends a response containing a Set-Cookie response header field

After that the client sends the cookie along with any following request:

  • client sends a request containing a corresponding Cookie request header field
  • server registers $_COOKIE key


Per the docs:

Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.

If you need it accessible on the same page, use sessions instead, or do a redirect to the same URL after the setcookie call.


Cookies are set / received as part of http headers exchange, so, under usual circumstances are one of the first thing the client (browser) sends / receives. For your problem, the client only knows it's got a cookie to send on the second request.

Using a good Firefox extension like Live HTTP Headers can help you discover which stuff's sent when.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜