Reputation: 1
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?
Upvotes: 0
Views: 1023
Reputation: 48357
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.
Upvotes: 0
Reputation: 5548
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.
Upvotes: 0
Reputation: 31730
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.
Upvotes: 1
Reputation: 5378
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;
Upvotes: 0