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.
Related
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
I'm guessing not, but is there a way to set a cookie in PHP without having to put ob_start() at the start of the output?
My problem is, that I am developing a class, which among others, needs to set a cookie. Now I can't tell the person who uses it "you have to make a new instance of the class before you make any output", cause that would be lame. So can I somehow pull it off?
See Headers already sent by PHP
The unprofessional workarounds listed there apply. Specifically:
<META HTTP-EQUIV="Set-Cookie"
CONTENT="cookievalue=xy;expires=Friday, 14-Dec-12 12:12:12 GMT; path=/">
Or use javascript and set document.cookie.
You cannot. Cookies are sent as part of the header, so if you've already sent the body, it's too late. Output buffering is the solution.
Perhaps you could use session variables instead.
This is my workround and is working fine for me.
// Force set cookie now
$_COOKIE['ref_url'] = $_SERVER['HTTP_REFERER'];
// Set cookie after refresh site
setcookie('ref_url', $_SERVER['HTTP_REFERER'], Affiliate::$cookieTime);
// Diplay $_COOKIE
var_dump($_COOKIE['ref_url']);
Bot of these lines:
echo '<br/><br/>'.$_SERVER["SCRIPT_NAME"]."?page=".$pager->GetVariableC."&threadID=".$threadID;
header("Location:".$_SERVER["SCRIPT_NAME"]."?page=".$pager->GetVariableC."&threadID=".$threadID);
Give me this:
/PoliticalForum/Thread/thread.php?page=2&threadID=6
Warning: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\PoliticalForum\Thread\comments.php:42) in C:\xampp\htdocs\PoliticalForum\Thread\thread.php on line 348
How do I redirect at the end of the script?
When this error happens, you have already sent something to the browser, by using echo or by having a couple of new lines after the closing php tag. Be sure not to have any new lines or echoing something before redirecting.
You can't redirect after you've sent output to the client's browser using PHP's header().
What you can do is use a meta tag:
<meta http-equiv="refresh" content="2;url=http://www.destination.com/">
Where 2 is the time before the redirect in seconds, and the url is the destination. You can find more information about it here (you should read the drawbacks section).
You can't redirect after you've already sent any data to the browser, in this case the first line is doing so. Why are you trying to print something that you are never going to see (The browser would be immediately redirected)?
Either remove the outputting lines above the redirect if possible, or look into using output buffers if you can't modify the surrounding code.
If you want output and a redirection then you need to use a javascript redirection. http://www.tizag.com/javascriptT/javascriptredirect.php
What you're doing here is called an HTTP redirection (an HTTP 302), which is one of the HTTP headers sent to the browser as a response.
This error message is due to the fact that you echo'd content which has the effect of sending out all the buffered HTTP headers then tried to set a header (but it was already sent). To get a much better view of this I recommend all web developers install firebug and monitor the "Network" tab, you'll really get a better grasp on headers and their meanings.
Cheers
<?
echo "lalala";
header("Location: http://www.google.com/");
If i put this in a plain php file and deliver over a standard apache2 server with mod-php (PHP Version 5.3.2-1ubuntu4.10) the redirect to google works.
<?
echo "lalala";
flush();
header("Location: http://www.google.com/");
this code does obviously not produce a working redirect.
My question is how the first code is beeing processed and why it works. Because I remember times when things like this were not possible. Is mod-php or apache intelligent enough to buffer the whole request and arrange headers before content?
And:
Can I rely on this if I make sure I don't flush the output manually? Because it would make my application much easier...
Output buffering is probably enabled by default. You should enable it manually if you want to rely on this functionality.
http://php.net/manual/en/function.ob-start.php
The header function ADDS an http common header to the HTTP response. So, the redirect is setted and the browser gets the 302 message before showing you the output.
flush orders php to send the http response already prepared at the point it is called. That's why the second code won't set the header (it must be setted before sending ANY output).
And, the PHP should not output a single thing until:
The script is processed (even if an error stops the parsing)
you set it to send the output somewhere in the script with flush()
Finally, check this on output control http://www.php.net/manual/en/intro.outcontrol.php
I would like to do the following in php :
setcookie('name', $value, $Cookie_Expiration,'/');
then some action
header("location:http://www.example.com")
the problem is that I get :
warning: Cannot modify header information - headers already sent by (...etc )
could you please let me know what i am doing wrong and if there is a way to do this?
by the way , this code is before any output is made ...the cookie setting part works fine on its own and so does the redirection code....the combination fails
thank you
Cookies are sent in the header, and you can't set headers if any output is already sent to the browser (which is is when you set the cookie).
The easiest solution, mind you it is a bit sloppy is to use ob_start() and ob_clean(), for example:
ob_start();
setcookie('name', $value, time()+3600);
ob_clean();
header("Location:http://www.example.com");
Please note the upper case L in the Location header, it is very important.
A better solution might be to set the cookie on the page you are redirecting to, and pass the information to set that header through a session.
From the php manual:
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.
basically saying what you already know from your warning; that the setcookie is itself sending a header. I'd probably wonder why you want to set a cookie on a page then redirect, why not just redirect and include the data in the URL then pick it up on the target page and use the data there and/or store it in a cookie then, or store in session data if you have a session set already.