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?
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With