As we’ve already discussed, the HTTP response that a server
sends back to a client contains headers that identify the type of content
in the body of the response, the server that sent the response, how many
bytes are in the body, when the response was sent, etc. PHP and Apache
normally take care of the headers for you, identifying the document as
HTML, calculating the length of the HTML page, and so on. Most web applications never need to set headers
themselves. However, if you want to send back something that’s not HTML, set the
expiration time for a page, redirect the client’s browser, or generate a
specific HTTP error, you’ll need to use the
The only catch to setting headers is that you must do so before any
of the body is generated. This means that all calls to
setcookie(), if you’re setting cookies) must
happen at the very top of your file, even before the
<html> tag. For example:
<?php header("Content-Type: text/plain"); ?> Date: today From: fred To: barney Subject: hands off! My lunchbox is mine and mine alone. Get your own, you filthy scrounger!
Attempting to set headers after the document has started results in this warning:
Warning: Cannot add header information - headers already sent
You can instead use an output buffer; see
ob_end_flush(), and related functions for more
information on using output buffers.
The Content-Type header identifies the type of document being returned. Ordinarily ...