Re: Not a question of how, but a question of why
| From: | Chris Adams | Date: | Thu, 27 Jul 2000 18:32:16 +0000 |
| Subject: | Re: Not a question of how, but a question of why | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-8630@lists.php.net to get a copy of this message | ||
> Why do the Header() and SetCookie() function have to be before any output
in
> PHP?
>
> Is it because CF is a two step process, parsing out the CFM, generating
> output, then passing it off to the web server to parse out the HTML and
> serve up? And PHP is a one step process?
Close. It's because Cold Fusion buffers the generated output by default.
Headers (cookies are just a single type of HTTP header) must be sent before
any of the page contents. With buffering enabled, the output will be saved
in memory on the server until the entire script is done. Since nothing will
have been sent to the client, a cookie may still be set.
In PHP, you can enable buffering in a script using ob_start(). There's a
configuration directive (output_buffering) which may be set in php.ini to
have buffering enabled by default.
However, before you do this, remember that it could have performance issues.
The biggest problem is in perceived load speed as, like CF, there won't be
anything sent to the browser until the entire script is done. If your page
does a lengthy operation (e.g. large query, pulling something from another
server, executing a program) it'll take awhile before the user sees
anything. If you want to send all of the buffered output before starting a
time consuming operation, use flush(). (There appears to be no Cold Fusion
equivalent, which I found greatly annoying.)
I would also recommend that you avoid writing pages where this is necessary.
They usually end up being hard to maintain. I prefer to have a script where
all of the input validation is done at the top before any of the HTML is
generated. In addition to eliminating the need for buffering, it's much
easier to change that sort of script six months later rather than searching
through a ton of HTML.
Chris