开发者

Why does SetCookie have to be called at the Beginning of an HTTP Response?

while reading about cookies i found difficulty to grasp the following statement

"setcookie() must be 开发者_如何学编程called before any output to the HTTP response. The main reason is that PHP is not buffering the HTTP response" please help me to interpret it in easy way


To understand that statement, you need to know a few things:

  1. HTTP responses consist of two parts, a set of "headers" (key-value pairs) and then the "body" which is the actual data e.g. a web page or image.
  2. HTTP headers have to be sent first, and once even one byte of the "body" has been sent, no more headers will be processed by the client.
  3. Cookies, among other things, are sent to the client in the form of HTTP headers.

So what it's saying is: unless you do something special, the instant you "echo" something or have any data outside a <?...?> block, PHP will begin the response body with that data. After that point, no more headers, including cookie-setting headers, can be sent.


It simply means that you need to ensure that all headers (cookies are set via HTTP headers) are output before any HTML code is output.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜