Unable to setcookie in any browser - php

So I have done a lot of reading on setting cookies and still cannot find what I am doing wrong here. I started with an if statement to include another script but it soon became clear the cookie wasn't setting so I simplified it and made it just to echo so I could see if it was setting. Its not. I am including it above the <html>.
I am setting the cookie and then refreshing and no matter how many times I refresh it is still returning a NULL result in the echo command.
The setcookie is above all of my html, cookies can't be set after any output??
The value is set, and domain.
All browsers have cookies enabled, and friends have tested this for me so its not local.
Its not the server, I asked my host.
I have even copy/pasted code from PHP manual to no avail.
And of course checked SO a few mil times.
$var='Something';
setcookie ("Name", "$var", time()+3600, '/', 'website.com');
echo $_COOKIE["Name"];
var_dump($_COOKIE["Name"]);
var_dump ($HTTP_COOKIE_VARS);
echo returning NULL and var_dump returning Array(0)
I am going mad, is there something wrong in my code, what am I missing?

The most frequent problem with setting cookies (or any other header) is, that it has to be set before you send first output character. There may be an invisible character before your script (like BOM or whitespace). If you use includes, thare may be a whitespace after the closing tag of your included script.

To debug cookies, one have to debug HTTP headers.
So, get yourself a Firebug, switch to Net tab and watch request and response headers, if you can see any cookie sent by server or returned by browser.
If there will be no trace of cookies - there is some error on the server side then. You need to enable error reporting and displaying in order to see them
ini_set('display_errors',1);
error_reporting(E_ALL);
is a quick and dirty way

Related

why is my cookie not set , is it my localhost? [duplicate]

I have a cookie that will not set on the remote server, works find locally. No error messages, var_dump gets me Null, echo is blank.
<php
setcookie('ymp','14', time()+3600);
session_start();
?>
I can set a javascript cookie fine. The opening tag is line 1 of the page.
Any ideas
Thanks
Gary
On Edit
I have some comments I posted below, it is a 3 file process.
Page one is to set the cookie, as above.
Page two I have for debugging
<php var_dump($_COOKIE['ymp']); echo'<br />'.$_COOKIE['ymp'];?>
Page 3, and again this all worked locally I have
<?php
if($_COOKIE['ymp']!=='14')
{die('Sorry, you have not had your delightful little pastry yet.... try again.');}
?>
I set a js cookie, and changed the code to reflect the different cookie name and it worked fine.
I also reset the time to +86400, because of the two hour time difference to the server, though I don't think that is really required.
Thanks for all the help
Gary
You can't read the value of a cookie until a new page request is made. This is because the value of cookie data is sent with the page request. So it isn't available for to access its value until after it is set and a new page request is made.
Also, session_start() has no effect on cookies. They are two different things. (Sessions do typically use cookies to store the session ID but that is irrelevant).
This is rather peculiar - I assume this could have something to do with PHP configuration.
See what the return value of setcookie function is - it may be FALSE if output has been already sent before the function call. You did mention it is right at the start of your script, however there could be other entities outputting data (pre-executed scripts on the server perhaps?)
It's also possible that your browser is set to not accept cookies from certain domain - check your configuration.
Please provide any other relevant code and indicate how you check if cookies are set.
This problem never did solve, I ended up writing a new file to a different domain on the same host, gave the cookie a different name and value (is it possible that a 3 character name cookie with a 2 digit value too small??) and it worked as supposed expected.
Thank you all for your help... too busy to do a CSI investigation as to the how's and whys.
Gary
It could be because you don't specify a path and/or a domain for the cookie. Try this instead:
<?php
setcookie('ymp','14', time()+3600, '/', 'yourdomain.com')
?>

header within html document not working - new server

I moved my documents to a new host and the headers stopped working(refresh,redirect,etc).They used to work in my old server.I have googled and tried adding a ob_start before sending headers, that did not work.
Here is a part of the code...
if(isset($_GET['reflink']))
{
echo '<h3>Already Logged In<h3><p>Please logout before registering an account.Redirecting you back to where you came from...';
header('Refresh: 3; url="http://www.xacnr.com'.$_GET['reflink'].'"');
}
*It used to work before, it must be a problem with the server settings or something :|
A short answer is:
It is not possible to send http headers after the output of anything else.
So if you want to output headers, you must do this at the beginning of your output. To be even more precise: HTTP-Headers must be the first thing of your output, if you have to send them - before anything else.
Please read the documentation:
http://www.php.net/manual/en/function.header.php
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
Please be also aware of the fact that the Refresh-Header is AFAIK not part of the official HTTP-Standard. It's a jurassic artifact from Netscape which will be still accepted and interpreted by most browsers, but this may change even without special notice.
If you need such a refresh and if you want to stay on the safe side, you should consider using the Meta-Refresh within the HTML-Header.
Please read here:
http://en.wikipedia.org/wiki/Meta_refresh
BTW: It's also a bad idea to use unsanitized, unprocessed values from $_GET, $_POST etc. Your example should never be used in any public available environment.
You do an output (echo) before you send the header:
echo '<h3>Already Logged In<h3><p>Please logout before registering an account.Redirecting you back to where you came from...';
header('Refresh: 3; url="http://www.xacnr.com'.$_GET['reflink'].'"');
The simple but strict rule is:
No output before the header!
From the Docs:
Remember that header() must be called before any actual output is
sent, either by normal HTML tags, blank lines in a file, or from PHP.
It is a very common error to read code with include, or require,
functions, or another file access function, and have spaces or empty
lines that are output before header() is called. The same problem
exists when using a single PHP/HTML file.

Cookie does not set

I have a cookie that will not set on the remote server, works find locally. No error messages, var_dump gets me Null, echo is blank.
<php
setcookie('ymp','14', time()+3600);
session_start();
?>
I can set a javascript cookie fine. The opening tag is line 1 of the page.
Any ideas
Thanks
Gary
On Edit
I have some comments I posted below, it is a 3 file process.
Page one is to set the cookie, as above.
Page two I have for debugging
<php var_dump($_COOKIE['ymp']); echo'<br />'.$_COOKIE['ymp'];?>
Page 3, and again this all worked locally I have
<?php
if($_COOKIE['ymp']!=='14')
{die('Sorry, you have not had your delightful little pastry yet.... try again.');}
?>
I set a js cookie, and changed the code to reflect the different cookie name and it worked fine.
I also reset the time to +86400, because of the two hour time difference to the server, though I don't think that is really required.
Thanks for all the help
Gary
You can't read the value of a cookie until a new page request is made. This is because the value of cookie data is sent with the page request. So it isn't available for to access its value until after it is set and a new page request is made.
Also, session_start() has no effect on cookies. They are two different things. (Sessions do typically use cookies to store the session ID but that is irrelevant).
This is rather peculiar - I assume this could have something to do with PHP configuration.
See what the return value of setcookie function is - it may be FALSE if output has been already sent before the function call. You did mention it is right at the start of your script, however there could be other entities outputting data (pre-executed scripts on the server perhaps?)
It's also possible that your browser is set to not accept cookies from certain domain - check your configuration.
Please provide any other relevant code and indicate how you check if cookies are set.
This problem never did solve, I ended up writing a new file to a different domain on the same host, gave the cookie a different name and value (is it possible that a 3 character name cookie with a 2 digit value too small??) and it worked as supposed expected.
Thank you all for your help... too busy to do a CSI investigation as to the how's and whys.
Gary
It could be because you don't specify a path and/or a domain for the cookie. Try this instead:
<?php
setcookie('ymp','14', time()+3600, '/', 'yourdomain.com')
?>

Setcookie does not set a cookie

Hi guys im trying to set a cookie using
setcookie("ms_il_cart_save_for_3", "cName", time()+3600);
header("Location: store-cart3.php");
exit;
when i am move to store-cart3.php the cookie was not set var dump on cookie shows NULL, this has work for me for a year by now. today i have updated changes no related to this piece of code, i know for a fact this worked so far, nothing is outputed with HTML before this code and i dont think i changed the files encoding, maybe my web server blocks creating cookie because of security mesures? (i have run this code today about 100 times)
this is pritty annoying any ideas?
Cookie setting will only work if headers haven't been sent yet. If you've already sent headers or content to the client then setcookie won't work. Setting cookies also requires the client to accept the cookie, if it doesn't then there's nothing you can do about that other than inform them that they need to accept cookies for your system to work.
EDIT: You said in your post that you made changes to unrelated code and now your setcookie doesn't work any more. It is possible that your unrelated code has an error in it that's causing PHP to echo an error message to the browser. This will cause all headers to be sent and any setcookie calls made after this point won't work.
When you're setting a cookie on a page that redirects in this manner, you have to set the cookie after the call to header().
So your example needs to be:
header("Location: store-cart3.php");
setcookie("ms_il_cart_save_for_3", "cName", time()+3600);
exit;
Propably you have outpuded some content before calling that functions and headers were already sent.
Try to start output buffering at start of your script by ob_start()
Also check your files for warnings/notices and BOM utf-8 bytes at begining of text file, wich ones aren't seen in text editor.
Is it browser specific? I've noticed that Blackberry browsers don't process cookies returned in a redirect response - but MSIE and Firefox are happy to.
Since the redirect is after the setcookie, I presume it would be fairly obvious if the headers had already been sent. But have you checked that the cookie is still in the response headers? (ieHTTPHeaders, firebug, tamperdata, fiddler, wireshark)
If not, try switching around the order of the setcookie() and header() calls.

what could some of the reason be to why a cookie wont be destroyed?

i have a cookie named MVCID that's set and its value is some generated hash.
when i write this
setcookie("MVCID","", time()-60*60*24);
and load the page, not only is the contents of the cookie not being erased but it also isn't dying.
what can be the possible problem? this isnt the first time this is happening.
ps: im also trying this on an empty page with no other code but this and it still wont die.
Try passing "/" as the fourth parameter -- path.
Are you calling this function before outputting any HTML? That's a known foible of the call since cookies have to appear in the HTTP header.
You might want to also check the time on the client side. Even though you're setting to expire one day ago, it's possible that the clock skew might be greater (if times aren't set correctly).
And I prefer to populate all parameters rather than relying on defaults (which can change based on many things).
In addition, you may want to check the return code although I have no idea how it could fail, something like:
<?php
$ret = setcookie("MVCID","", time()-60*60*24);
?>
<html>
<head></head>
<body>
Hello<br>
<pre>
<?php
print_r ($ret);
?>
</pre>
</body>
</html>
Failing that, you may need to have a look at what's going on at the wire level. In other words, examine the HTTP response to ensure there's a Set-Cookie in the HTTP headers and examine the actual values being passed along with it.
And one last trick to try: delete the cookie totally and exit from the browser (some of them cache in memory). Then try again. If the PHP setcookie is not working then no cookie will be created - the one you have that's not being changed or expired may be left over from a previous successful variant of your code.
Use something like firebug or fiddler to examine the actual response headers (both, the one containing the "real" cookie and the one containing the "delete" cookie)

Categories