We shouldn't really bother with your question as you didn't take any advice from your previous question about the exact same problem, but here goes:
Option A
// As you do setCookie, also set the value in $_COOKIE
setCookie("foobar", "bat", time() + COOKIE_LIFETIME);
$_COOKIE["foobar"] = "bat";
var_dump($_COOKIE["foobar"]);
Option B
Don't use $_COOKIE
to store your information. Have separated variables $token
, $secret
and $key
and load these with the values from $_COOKIE
. If $_COOKIE
is empty, initialize them manually and call setCookie
.
if (isset($_COOKIE["token"]))
$token = $_COOKIE["token"];
else
{
$token = "defaultValue";
setCookie("token", $token, COOKIE_LIFETIME);
}
// Use $token instead of $_COOKIE["token"] from now on.
Option C
If the user does not have the cookies set, do setCookie
and relocate the user to the same site again with header()
. Beware of infinite relocates if the user does not allow you to set cookies.
if (!isset($_COOKIE["token"])
{
setCookie("token", "defaultValue", COOKIE_LIFETIME);
header("Location: ".$_SERVER["REQUEST_URI"]); // insert reasonable URL here.
exit;
}
Option B would be the preferred one. Hope to not see this question asked a third time.
You can't check in the same request if the user will send your cookies in future requests. setCookie
is merely an appeal to the users browser to please attach this information to future requests. You will know if it works, if the cookie is send on the next request. If it does not following 3 scenarios are possible: a) The user's browser does not allow you to set cookies, b) the user has not visited your website before, c) previously set cookies have expired.