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
views:
60answers:
2
+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
2010-07-10 14:16:35
actually thats fine sir,but i am concern about the reason
fluty
2010-07-10 14:57:07
@fluty Headers must be sent before the body of an HTTP response. That is just the way HTTP works.
Alex JL
2010-07-10 15:02:56
+5
A:
To understand that statement, you need to know a few things:
- 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.
- 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.
- 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
2010-07-10 14:58:20
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
2010-07-10 16:15:11
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
2010-07-10 17:44:39