Current Location: Home> Latest Articles> A Detailed Guide to the header() Function in PHP: Controlling HTTP Response Headers

A Detailed Guide to the header() Function in PHP: Controlling HTTP Response Headers

M66 2025-07-27

What Does the header() Function Do in PHP?

The header() function is a built-in PHP function that is used to control the HTTP headers sent by the web server in response to client requests. With this function, you can set various response headers before any page content is output, allowing you to manage browser behavior and server responses.

Page Redirection

One of the most common uses of the header() function is for page redirection. In PHP, you can use header() to redirect users from one page to another.

Redirection Example

header('Location: URL_HERE');

Setting Content-Type

By default, PHP sends the Content-Type header as text/html. If you need to send other types of content, such as PDF or JSON, you can use the header() function to modify the Content-Type header.

Setting Content-Type Example

header('Content-Type: application/pdf');

header('Content-Type: application/json');

Setting HTTP Response Status

The header() function also allows you to set the HTTP response status. For example, if a page is not found, you can return a 404 error.

Setting HTTP Status Example

header('HTTP/1.0 404 Not Found');

Controlling Browser Cache

If you want to prevent a browser from caching a page, you can set the appropriate Cache-Control header. The following example shows how to use the header() function to prevent caching.

Preventing Cache Example

header('Cache-Control: no-cache, must-revalidate');

Conclusion

The header() function is an essential tool for controlling HTTP response headers in PHP. With it, you can perform tasks like page redirection, modifying Content-Type, setting HTTP status codes, and managing cache control, which greatly enhances the flexibility of your development process. Mastering the use of the header() function is an important skill for PHP developers.