why unset cookie variable when deleting cookie - php

I'm exploring the source code of Kohana framework, and it has the following logic when deleting the cookie on browser:
public static function delete($name)
{
// Remove the cookie
unset($_COOKIE[$name]);
// Nullify the cookie and make it expire
return setcookie($name, NULL, -86400, Cookie::$path, Cookie::$domain, Cookie::$secure, Cookie::$httponly);
}
I understand that the function setcookie will set cookie's name to deleted (as displayed in browser cookies view) and expire it so that the browswer doesn't send it next time. So why is the first part with unset is there?

setcookie add cookie to HTTP response headers. Whereas $_COOKIE presents cookies from request headers. So setcookie doesn't affect on cookies of $_COOKIE array (on the current page load). Therefore we have to unset cookie in $_COOKIE too in order to ensure that this cookie won't present in $_COOKIE array if we'll want to get it in further (on the current page load).

both are same and deleting cookie. If we remove unset, Surely it will work and delete the cookie.

Related

asking about the cookie after logout

I'm trying to access a cookie's value (using $_COOKIE) immediately after calling the setcookie() function in PHP. When I do so, $_COOKIE[$cookiename] isn't set after login. Why?
if(isset($_SESSION)){
$_SESSION['email']=$username;
$_SESSION['id']=$query['id'];
$_SESSION['name']=$query['name'];
$_COOKIE[$cookiename]=$query['name'];
$cookiename="user";
$cookie_value = "John Doe";
setcookie($cookiename,$cookie_value, time() + (86400 * 30),"/");
if (!$session->Check()){
echo $cookiename ;
}else {
echo $_COOKIE[$cookiename];
}
This is because when you call setcookie() you are attaching the cookie to the current response(when the current request completes).
$_COOKIE will have a value when a request is made with the cookie header already set i.e cookie is sent to the server.
So, when only #1 happens you don't have anything in $_COOKIE, but once #2 happens you will have a value in $_COOKIE
EDIT: Almost everything you need is mentioned in the manual
http://php.net/manual/en/function.setcookie.php
setcookie() defines a cookie to be sent along with the rest of the
HTTP headers Once the cookies have been set, they can be accessed on
the next page load with the $_COOKIE array. Cookie values may also
exist in $_REQUEST.

difference between setcookie and $_COOKIE in php

Is there any difference between setting a cookie via setcookie() and $_COOKIE ?
Sometimes,when setting a cookie via setcookie,i don't get the value of that cookie via $_COOKIE['cookie_name'].But js console.log immediately after setcookie,shows that cookie is set but if i try to get the value of the cookie via $_COOKIE,i don't get the updated value.
I'm confused..!!
You can't actually "set" a cookie with some code like this:
$_COOKIE['cookie'] = $my_var;
All this does is add a new value to the $_COOKIE array. No Set-Cookie HTTP header is sent back to the client (browser) in the response and no cookie will be created on the client.
Use the setcookie() function to set cookies.
The current accepted answer correctly points out that $_COOKIE is set/initialized at the start of the PHP process and isn't updated after that. You can update it yourself but don't expect that value to stick on the next request.
In setcookie function you can only set the cookie name.
If you want to get that cookie value then you can take it via the $_COOKIE['name']
Be sure that when you create cookie you need to set domain name in setcookie function as well.
In PHP, we can set a cookie with the function setcookie(). The syntax of the function is
setcookie(name,value,expire,path,domain,secure)
For example, setcookie('name',$name,0,'/');
will create a cookie named name with value of the variable $name in the root directory '/'. Inorder to access the cookie, we can use $_COOKIE['cookiename'];
With setcookie you can only set cookie in php :
setcookie("myCookie", $value, time() + 3600);
But if you want to get or use that cookie you can use $_COOKIE, like if you want to get some cookie value use:
echo $_COOKIE['cookie_name'];

Why does this PHP setcookie() argument not set a cookie?

I have this PHP
setcookie('hello', '0', 0, '/389732/');
Why when I run it does it not set a cookie?
I printed the value of $_COOKIE['hello'] out immediately after and it puts out an error because it does not exist.
setcookie documentation spells this out:
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE ...
Edit: it might be tempting to manually insert that cookie into $_COOKIE yourself, but keep in mind that some frameworks helpfully parse $_COOKIE into other data structures on startup and will not see such hackish changes.
$_COOKIE gets populated when the script first runs. setcookie puts the cookie info in a queue that gets turned into a header when the page returns to the browser.
When the browser requests a new page, it sends the cookie information back to your server and the $_COOKIE variable will be populated.
Because the $_COOKIE is the content of the cookie when the php was called.

see if cookie exists on the same file as they were set

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..
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
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.

Can't set PHP cookie on the same page

I'm having trouble setting cookies on the same page. I used cookies on my site and it works fine, I tend to set make the php in separate file. Now, I'm setting a cookie on the same page but it doesn't seem to work.
$expire = time()+5;
setcookie("rb_vote", 1, $expire);
then check if it is set
if(isset($_COOKIE["rb_vote"])) {
echo "IS SET";}
else {
echo "IS NOT SET"; }
It always says is not set. I tried doing this in page load but still doesn't work.
See the manual on setcookie() (emphasis mine):
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays. Note, superglobals such as $_COOKIE became available in PHP 4.1.0. Cookie values also exist in $_REQUEST
Here is a workaround suggestion. It's imperfect because it can't guarantee the cookie actually gets set, but might do in your case.
I've just encountered this issue in Vanilla Forum. On the first page load, before a session has been established, a session cookie is created, but then every time the application wants to access the session variables (to add to them) it looks for the current session ID in $_COOKIE, which is not set until the next page load.
My workaround is to set the $_COOKIE element manually when the cookie is created.
// Create a cookie to identify the session.
// This line already exists. $Name is the cookie name.
// $SessionID is a random md5 ID that has just been generated.
setcookie($Name, $SessionID, $Expire, $Path, $Domain);
// Set the cookie for the remainder of the page. This is a workaround.
if (!isset($_COOKIE[$Name])) $_COOKIE[$Name] = $SessionID;
I've raised this as a fault with Vanilla (https://github.com/vanillaforums/Garden/issues/1568), as this workaround feels like a bit of a hack, but it certainly gets around the problem for now.
PHP5.3 Vanilla Forum Version 2.0.18.4

Categories