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.
Related
This is a small test. I set a cookie and then try to access it:
<?php
setcookie("t",0,time()+900);
echo ($_COOKIE['t']+10);
setcookie("t",0,time()-3600);
?>
When I run the code I get an error message as below:
Notice: Undefined index: t in /var/www/x/testcookie.php on line 5
10
Why can't I access the cookie?
It doesn't work that way. setcookie just says "with next http connection tell client (browser) to set this cookie. The browser sends it back in next http connection, if it has not expired yet. Only then it is contained in $_COOKIE array. So you can check that it is set in PHP after next page reload.
Besides in your code second cookie will not be set, because you outputted something to the browser which is forbidden before setcookie function (any header function).
setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.
Once the cookies have been set, they can be accessed on the next page
load with the $_COOKIE
you need understand how cookies works. with setcookie you sent header to browser, which tells browser to store cookie. And $_COOKIE superglobal contains cookies which comes from user request headers. so it means that variable which you set with setcookie only be available in $_COOKIE array after refresh, when it comes back with user request headers. And remember that set headers you can only before any output, so second setcookie will not work.
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.
I am facing a difficulty in understanding the usage of cookies in PHP,
Please consider the following code snippet
public function preExecute() {
setcookie("testCookie", "Hello123", time() + 31536000, "/", WebServer::getServerName());
echo "Before Value of cookine in decommission::".$_COOKIE["testCookie"];
setcookie("testCookie", "Hello456", time() + 31536000, "/", WebServer::getServerName());
echo "After Value of cookine in decommission::".$_COOKIE["testCookie"];
}
The output that i am expecting for this code
Before Value of cookine in decommission::Hello123
After Value of cookine in decommission::Hello456
But the output i am getting for the above code snippet is
Before Value of cookine in decommission::Hello456
After Value of cookine in decommission::Hello456
Will appreciate if someone explain me the working, i have gone through resources available in internet, but still i am not clear.
Thanks in advance.
$_COOKIE holds the cookies that have been received in the current request. It is not automatically updated when you call setcookie to set cookies in your response. The cookies you set via setcookie will only appear in $_COOKIE on the next request, when the cookies are sent back to the server.
So what you're seeing is that the second cookie overwrites the first, so only the later value is sent back to the server. I'll guess you have refreshed the page several times already, so you're seeing the cookie. If you clean your cookies and run this again, on the first try you won't see any output, because $_COOKIE is empty and stays empty for the whole request, no matter how often you call setcookie.
If you dont want to change this usage, use sessions. $_SESSION is a global array. You can reach from everywhere (inside class,function) and use instantly (no need to wait next request/page load).
I am trying to setup a session management with cookies in PHP.
My code is as follows:
if(empty($_COOKIE )) {
setcookie('session_id', md5(uniqid()), time()+(EXPIRE CONSTANT));
}
$session_id = isset($_COOKIE['session_id']) ? $_COOKIE['session_id'] : 0;
I will then check session_id for 0 and print an error message if cookies are disabled.
This works fine if cookies are really disabled.
The problem is, if a user clears his history the first time he visits
the site he will get the error message even if cookies are enabled.
Anyone have any clues about this ?
Thank you in advance
When you do the setcookie call, the cookies will be sent when the header is output to the browser. This means the cookie won't be available until the next page load (when the client sends the cookie back to the server). This is mentioned in the php manual for setcookie http://php.net/manual/en/function.setcookie.php:
setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script (this is a protocol restriction). This requires that you place calls to this function prior to any output, including and tags as well as any whitespace.
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.
You won't be able to determine if cookies are enabled/disabled until the page has reloaded (from php). I think you'll have to do this check with javascript, or to stay in php do a redirect after setting the cookie for the first time, something like:
if(empty($_COOKIE)) {
if (isset($_GET['cookieset'])) {
// do error message, cookie should be set
}
setcookie('session_id', md5(uniqid()), time()+(EXPIRE CONSTANT));
header('location: http://mysite.com/index.php?cookieset=1');
exit;
}
$session_id = isset($_COOKIE['session_id']) ? $_COOKIE['session_id'] : 0;
#bencoder : I have done the test on iPad and Chrome/PC : you are right for iPad, you do need to refresh the page before you can read the cookie data, but on Chrome/PC, after deleting all cookies, if you set a new one from PHP, you can perfectly get the values directly on the first page load. Why ? There must be a more precise explanation. Why two different behaviors? Does the order of this output/availability of the data depend on the browser request to the server? Interesting to know...
I am trying to set a cookie for a site if it does not exist. It is not working.
if(isset($_COOKIE['about'])){
$_COOKIE['about'] += 1;
}
if(!isset($_COOKIE['about'])){
setcookie("about", 1, time()+3600);
}
I have also tried
if(empty($_COOKIE['about'])){
setcookie("about", 1, time()+3600);
}
The $_COOKIE superglobal is only available for you to read values from. Writing to it does not update the cookie, since that requires a new Cookie header to be sent to the browser. You would probably be better served by sessions backed by cookies, since PHP allows you to modify the session without explicitly saving/setting the cookie.
You can only read stuff from the $_COOKIE superglobal, try setting it normally:
setcookie("about",$_COOKIE['about']+1,time()+3600);
So all together:
if(isset($_COOKIE['about'])){
$_COOKIE['about'] += 1;
}else{
setcookie("about", 1, time()+3600);
}
Note the else, you've checked before if the cookie isset, so there is no need to check again as either it is or it isn't.
Make sure you have not sent any information to the user yet as the setcookie call is just an alias to header() (but with a specific schema to follow). You may have error output disabled and are missing the message, so it appears to work but is failing in the background.
setcookie should be one of the first calls on your page, up there with starting a session and setting a header.