Setting Response Headers

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 header() function.

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 header() (or 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_start(), ob_end_flush(), and related functions for more information on using output buffers.

Different Content Types

The Content-Type header identifies the type of document being returned. Ordinarily ...

Get Programming PHP, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.