How to set a cookie for a domain in PHP? - php

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.

Related

PHP - Working of Cookies

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

Php cookie not setting

Alright I'm totally baffled.
Here's my code:
if ($password == $correct_password[0] && !isset($_COOKIE['user'])) {
setcookie("user", $email, time() + 3600);
var_dump(isset($_COOKIE['user']));
echo "!";
}
So it's doing the var_dumps, meaning that the setcookie should called. But the line right after it (checking if it's set) says it's not set!
If anyone could point out the problem it'd be greatly appreciated. Thanks
$_COOKIE is populated/loaded when the script first starts up, and then is NOT updated by PHP again for the life of the script. Setting a cookie via setcookie will only show up in $_COOKIE on the NEXT execution of the script.
This applies to all of the superglobals, except $_SESSION. They're populated/initalized at script startup and then PHP does not ever touch them again. $_SESSION is populated when you call session_start() (or sessions are set to auto start), which may be done multiple times within a script's lifetime.
PHP is a server-side language.
That means that it can generate whatever it wants and will then pass it to the client.
And that's it.
There is no back and forward on a single request.
1º you instruct the page 'A' to set a cookie
2º client recieves page 'A' and sets the cookie
3º client asks for page 'B' (sending the cookie)
4º server can identify the cookie (only on page 'B')
Page here is used as simple way of understanding a server call.
You can request the same page twice for the purpose.
Still didn't find a solid valid answer, but after endless hours of testing it seems like something with the time. If I set the expiration date too close to the real time, maybe it doesn't register or something. It seemed to work when I set the time further, but I'm taking a break before heavy testing again.
Thanks
When you use setcookie() it will save its value the next time that the HTML is loaded. If you want to see the vardump with the value you just assigned you will need to use $_COOKIE['cookie_name'] = $value;

Cookies cannot be set the first time after clearing history in Firefox

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

Problem with cookies detection in PHP

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.

how to use variable in setcookie()?

I want to pass a variable set by the user to the setcookie function.
I would like to let user change the color of some parts of website. so far the information about color is sent to server with $_SESSION['colorcode'] and I would like to add it to setcookie as well so when the user logs in to the site next time, his/her color is there.
I've got this code:
setcookie(
'colorcode',
$_SESSION['colorcode'],
time() + 60 * 60 * 24 * 30,
'',
'',
false,
true
);
I would like to save the value of variable in cookie, but it works just for the session.
what is wrong? how to do it so the color is there when the user logs in? I'm looking for another way than storing it in database or file.
Did you read back the value from the cookie at the beginning of the next session? Setting the cookie looks good but I think the last parameters could be omitted.
setcookie("colorcode", $_SESSION['colorcode'], time()+3600*24*30, '/');
Perhaps even the path ('/') is optional. But this only sets the cookie. You have to read the data back in, when the user returns to your site the next time.
if ( !isset($_SESSION['colorcode']) and isset($_COOKIE['colorcode']) ) {
if ( preg_match('/^#?[0-9a-fA-F]{6}$/', $_COOKIE['colorcode']) ) {
$_SESSION['colorcode'] = $_COOKIE['colorcode'];
} else {
// bad value... delete cookie if you like
}
}
When there is no colorcode in the session but the cookie-value exists, then the data is validated and if it's a valid 6 digit hex color code, then the value is inserted into the session. The validation is nessessary because a cookie is data that comes from the user and therefore potentially malicious.
This should work just fine:
setcookie("colorcode",$_SESSION['colorcode'],time()+60*60*24*30);
Just make shure you output it in the headers, I guess:
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.
Do you get errors?
Try to check this:
setcookie('colorcode',$_SESSION['colorcode'],time()+60*60*24*30);
since cookie related functionalities (setcookie(), ...) work with HTTP headers, you should user them before any output is sent to client. but this does not mean these functions should appear at the beginning of your code. just make sure no output has been sent. even a single space character at beginning of your file outside of

Categories