views:

60

answers:

2

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

+2  A: 

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.

middaparka
actually thats fine sir,but i am concern about the reason
fluty
@fluty Headers must be sent before the body of an HTTP response. That is just the way HTTP works.
Alex JL
+5  A: 

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.

Walter Mundt
+1 - Better explanation than mine. :-)
middaparka
thankz amazing explanation sir,but the statement "The main reason is that PHP is not buffering the HTTP response",does buffering allow to chnage the order?
fluty
Yes, if you enable output buffering, you are telling PHP to hold onto output until you are ready to do something with it. Look up the ob_start and ob_end_flush calls in the PHP manual. Basically, you call ob_start early, and ob_end_flush when you're ready for PHP to send data to the client.
Walter Mundt
thank you sir :)
fluty