PHP Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 3.00

header() - Inserting a Raw Header Lines

This section describes how to use the header() function to insert a raw HTTP response header line to reset the status line, replace an existing header line, or add a new header line.

When a PHP page is requested, the PHP engine will add some basic header lines in the HTTP response. But if you want to add new header lines or change those inserted by the PHP engine, you can use the header() function. Here are some rules on how to use the header() function:

1. The syntax of header() is:

void header(string $line, bool $replace, int $code)

2. $line specifies a complete header line string like "Content-Type: text/html".

3. $replace specifies a Boolean value controlling whether to replace a previously defined header line of the same identifier or not. If $replace = TRUE, the specified header line will replace any existing header lines with the same identifier. If $replace = FALSE, the specified header line will not replace any existing header lines with the same identifier. If $replace is not provided, PHP will assume $replace = TRUE.

4. $code specifies an integer to be used as the HTTP response status code. If $code is not provided, the PHP engine will decide the status code.

5. header() must be called before any output to the entity body, if the output buffering is turned off.

6. If header() is called to set "Location" header line, the status line will be set to "HTTP/1.0 302".

7. When header() is called multiple times, the status line will be always generated first. Other header lines will be generated in same order as their calling statements.

Here a sample PHP script code segment that generates some header lines using the header() function:

   header("HTTP/1.1 200 OK"); // Reset the status line
   header("Cache-Control: no-cache, must-revalidate");
   header("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); // Past time ok
   header("Content-Type: text/html; charset=utf-8");
   header("Content-Length: 9490");
   header("My-Header: SID=909494909", FALSE); // Allow duplicates
   header("My-Header: UID=Herong", FALSE); // Allow duplicates

Last update: 2005.

Sections in This Chapter

What Is an HTTP Response?

HTTP Response Header Lines

header() - Inserting a Raw Header Lines

HttpRequestGet.php - Viewing Header Lines

Response Header Lines of Static Files

HttpHeaderLines.php - Examples of Inserting Header Lines

Location: - Forcing the Browser to Redirect to Another URL

Content-Type: - Generating Non-HTML Response Body

Content-Disposition: - Sending Files for Downloading

Dr. Herong Yang, updated in 2009
header() - Inserting a Raw Header Lines