-1

In a file I have this code to set some cookies

setcookie("token", "value", time()+60*60*24*100, "/");
setcookie("secret", "value", time()+60*60*24*100, "/");
setcookie("key", "value", time()+60*60*24*100, "/");

I want to know how I can check if these cookies were set on the same file, preferably just after they're set. I have tried this

if(!isset($_COOKIE['token']) || !isset($_COOKIE['secret']) || !isset($_COOKIE['key']){

//do something

}

but it doesn't work..

Frank
  • 1,844
  • 8
  • 29
  • 44
  • Cookies are only set when they are sent back to the browser, and can only be tested by PHP when the browser issues a new request... so "No! they don't exist in the script in which they were set" – Mark Baker Feb 23 '12 at 15:10
  • Dupe: http://stackoverflow.com/questions/9415282/php-cookie-isset – AndrewR Feb 23 '12 at 15:11
  • Superglobals are set when the script is started up, then PHP does NOT change them to reflect anything you've done within the script. – Marc B Feb 23 '12 at 15:21

2 Answers2

0

the $_COOKIE is set when the user already have a cookie and ask for a new page.

You can't setcookie then use $_COOKIE right after

Nettogrof
  • 2,116
  • 2
  • 15
  • 22
0

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.

Basti
  • 3,998
  • 1
  • 18
  • 21