Semantics of setting cookies and redirecting without getting header error
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 I get: warning: unable to change header information - headers already sent (... etc)
Could you please let me know what I am doing wrong and if there is a way to do this?
btw this code is before any output is executed ... the cookie setting part works fine on its own, and also the redirect code .... combination of fail
Thank you
a source to share
Cookies are sent in the header and you cannot set the headers if any output has already been sent to the browser (this is when you set the cookie).
The simplest solution, of course, is a bit careless for you to use ob_start()
and ob_clean()
, for example:
ob_start();
setcookie('name', $value, time()+3600);
ob_clean();
header("Location:http://www.example.com");
Note the uppercase L in the Location header, this is very important.
The best solution might be to set a cookie on the page you are redirecting to and pass the information to set that header through the session.
a source to share
From php manual:
setcookie () defines the cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any exit from your script (this is a protocol limitation). This requires that you send calls to this function before any output, including tags as well as any spaces.
basically says what you already know from your warning; that setcookie sends the header itself. I am probably wondering why you want to set a cookie on the page and then redirect, why not just redirect and include the data in the url and then pick it up on the landing page and use the data there and / or store it in a file cookie then or store in session data if you already have a session established.
a source to share