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.
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.
header(
'Location: URL_HERE'
);
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.
header(
'Content-Type: application/pdf'
);
header(
'Content-Type: application/json'
);
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.
header(
'HTTP/1.0 404 Not Found'
);
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.
header(
'Cache-Control: no-cache, must-revalidate'
);
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.
Related Tags:
header