Here is the simple function that I'm using:
public function control() {
$string = 'lolcheck';
setcookie($string, $string, time() + 120, $this->path, $this->domain);
if (isset($_COOKIE[ $string ])) return true;
else return false;
}
The problem is that it only works when I open the page twice, because it gets the previously set cookie.
Apparently everyone suggest to use this practice, but its not working for me.
Am I missing something?
Cookies do not work that way. When a cookie is set, it is not available (i.e. a corresponding $_COOKIE key exists) until the next request.
What actually happens is:
client sends a requests
server sends a response containing a Set-Cookie response header field
After that the client sends the cookie along with any following request:
client sends a request containing a corresponding Cookie request header field
server registers $_COOKIE key
Per the docs:
Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
If you need it accessible on the same page, use sessions instead, or do a redirect to the same URL after the setcookie call.
Cookies are set / received as part of http headers exchange, so, under usual circumstances are one of the first thing the client (browser) sends / receives. For your problem, the client only knows it's got a cookie to send on the second request.
Using a good Firefox extension like Live HTTP Headers can help you discover which stuff's sent when.
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.
This is taken directly from w3's website. I may not be understanding cookies correctly, but why is nothing displaying?
$expire=time()+60*60*24*30;
setcookie("user", "Alex Porter", $expire);
echo $_COOKIE["user"];
Your cookie will only be accessible when you refresh the page or navigate to a new one.
When your script loads, the HTML header fields for that page have already been set. The page will need to be rendered again (another HTTP transaction) before your cookie is available for use. Check PHP's documentation:
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
check that your browser allows localhost / 127.x.x.x cookies or not ? if it allows then refresh the page. If you are using Google Chrome then you can see all browser cookies from here : chrome://settings/cookies navigate to localhost / 127.x.x.x to see your code has put cookies or not !
The variable $_COOKIE[] representates the state at the start of the script. That means that you have to wait on the next page request to see the variable. You could also add your variable manually to the global cookie variable $_COOKIE['user] = 'Alex Porter'; but the problem is that you are not sure that the browser really accepted the cookie.
I want to set a cookie via PHP. The scenario is like this:
Domain is: example.com
There is one web page on sub-domain (my.example.com). My code is:
$value="I am looged in";
setcookie("TestCookie", $value,'','',".example.com");
echo "hello".$_COOKIE["TestCookie"];
but the result is only "hello" - the cookie is not getting set.
First two corrections to the actual call of setcookie: Parameter 3 (expired) should be an integer value (the default value is 0); parameter four should be set to '/' to make the cookie valid for all subdirectories; the setcookie call should therefore look like this:
setcookie("TestCookie", $value, 0, '/', ".example.com");
Then it should actually work the second time the script is called. To understand why it won't work the first time already, we have to dig in a little into how cookies work; basically, Cookies are data sent from the server to the client, where the server says "send me this data the next time you send me a request". That's basically what setcookie is for: When the request is done and the client has received and processed the page, the cookie as specified will have been created at the client; $_COOKIE, on the other hand, holds all values which are in cookies already, and which have been transmitted by the client along with the request - meaning that the first time the script is called, $_SESSION will actually still be empty, since the cookies will only be created once the client has received the scripts output.
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.