Using PHP's header() Function: Redirects, HTTP Headers, Status Codes, Caching, and File Downloads
This article provides a comprehensive guide to PHP's header() function, covering its syntax, parameters, and five common scenarios—including page redirects, setting response headers, status codes, cache control, and file downloads—along with clear code examples and best‑practice tips.
In PHP, the header() function is a fundamental tool that can perform page redirects and set HTTP response header information. This article details how to use header() and provides concrete code examples.
The basic syntax of the function is:
header(string $header, bool $replace = true, int $http_response_code = 0): bool$header (required): The HTTP header to send, e.g., "Content-Type: text/html;charset=utf-8".
$replace (optional): Whether to replace a previous header of the same name. Default is true .
$http_response_code (optional): An HTTP status code to send with the header.
Below are five common use cases for header() with specific code snippets.
1. Implementing a Web Redirect
The function can redirect a user to a specified URL:
header("Location: http://www.example.com");
exit;2. Setting HTTP Response Headers
It can also set various response headers such as Content-Type :
header("Content-Type: application/json");3. Setting HTTP Response Status Codes
Use it to send a specific status code, for example a 404 Not Found:
header("HTTP/1.1 404 Not Found");4. Preventing Page Caching
By sending cache‑control headers you can tell browsers not to cache the page:
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");5. Enabling File Downloads
Set Content-Disposition to "attachment" and provide appropriate headers to trigger a file download:
header("Content-Disposition: attachment; filename=example.pdf");
header("Content-Type: application/pdf");
header("Content-Length: " . filesize("example.pdf"));
readfile("example.pdf");Conclusion
The header() function is essential for controlling HTTP behavior in PHP applications, allowing redirects, custom headers, status codes, cache control, and file downloads. It must be called before any output is sent, and it is advisable to follow it with exit to prevent unintended script execution.
By mastering header() , developers can flexibly manage HTTP responses to meet a wide range of requirements.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.