[FAQ] Why Can't I Send Headers?-VBForums
Results 1 to 1 of 1

Thread: [FAQ] Why Can't I Send Headers?

  1. #1

    Thread Starter
    Join Date
    Jan 2005

    Arrow [FAQ] Why Can't I Send Headers?


    Headers are one-line HTTP directives that are sent before the body of the response. The headers tell the user agent how to handle the response body, and give it any extra information that might be required. The most important functions of headers are to communicate the MIME content type of the response body, to perform redirections, and to set cookies.

    In PHP, you can set a header explicitly by using the header function, or implicitly by using a function that requires them, such as setcookie or session_start (although sessions can optionally be used without cookies and thus without headers).

    The Problem

    Because headers are supposed to be sent before the response body, you may run into trouble when you try to set a header after transmission of the response body has begun. Specifically, you'll receive the following warning:
    Warning: Cannot modify header information - headers already sent by (output started at D:\dev\php\test.php:3) in D:\dev\php\test.php on line 4
    This warning occurs because, by default, PHP flushes headers as soon as you begin sending output. This includes echo/print/print_r/var_dump calls and any content outside <?php...?> tags.

    The Fix

    This problem is caused simply by badly designed scripts. As a matter of good practice, logic and presentation should be kept separate, and so all processing should take place before any output is sent. This allows you to decide whether or not any headers should be set before it is too late to set them.
    If you are already doing this, then you can find the error quickly by inspecting the warning message: "(output started at D:\dev\php\test.php:3)" tells you exactly where to look to fix the error.

    There are also several workarounds. One easy way to suppress the problem is to enable output buffering, which will stop the headers from being flushed until you either overflow the output buffer, manually flush it, or the end of the script is reached. However, this masks the problem rather than solving it, and can lead to badly structured code; furthermore, output buffering hampers performance slightly. Buffering should only be used for a specific purpose, rather than to avoid problems caused by bad script design.

    Copyright 2007. Unauthorised reproduction prohibited.
    Last edited by penagate; Nov 8th, 2007 at 12:39 AM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts


Click Here to Expand Forum to Full Width

Survey posted by VBForums.