php set cookie issue

Rafay picture Rafay · May 9, 2011 · Viewed 8.1k times · Source

I'm setting a cookie on localhost with the following syntax

setcookie("testCookie ", "hello cookie", false, "/", false);

The problem is the first time I visit the page the cookie is created and firebug shows

Cookie testCookie added.  hello cookie

But it does not read the value. If I refresh the page, the value is read and fire bug shows

Cookie testCookie changed.  hello cookie

How can I get the value of the cookie to be read the first time the page is loaded?

Answer

Rudi Visser picture Rudi Visser · May 9, 2011

As I put in my comment, from your description (although fairly vague and not too understandable), I think the issue may be that you're trying to read the cookie before it's sent to the server.

The way a cookie works is as follows:

  1. You make a request
  2. Server SENDS cookie header back to client
  3. Page loads - Cookie is NOT visible to PHP on this page load
  4. Refresh
  5. Client SENDS cookie header to server
  6. Server RECEIVES cookie header thus PHP can read it
  7. Page loads - Cookie IS visible here.

If you haven't tried already, refresh again!

Since you want to read it at the same time you're setting it, just store the value you're setting and use that. Alternatively (although this is untested), you could manually set it in the $_COOKIE array.

So something like this:

setcookie("helloworld", .. );
$_COOKIE['helloworld'] = $value;

Then you can read it normally. Note that I wouldn't really recommend overriding the value of an automatic superglobal (same goes for $_REQUEST, $_POST, $_GET, etc.), and would instead suggest that you just store the value you're setting and use that.


Another approach would be to use a form of "gateway", meaning you'd set the cookie on a gateway page, which will then continue to redirect you to the next page.

For example, say your flow was as follows: login.php -> account.php. Rather than POST'ing your login form straight to account.php you have 2 options.

Opt 1: POST back to login.php, set the cookie, and then redirect to account.php. Opt 2: Have a gateway, such as logincheck.php, POST through to that, set the cookie, and then redirect to account.php.

This way, account.php can always see your cookie.