开发者

Semantics of setting cookies and redirecting without getting header error

开发者 https://www.devze.com 2022-12-30 09:07 出处:网络
I would like to do the following in php : setcookie(\'name\', $value, $Cookie_Expiration,\'/\'); then some action

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消