Using PHP header() Function: Redirects, HTTP Headers, Status Codes, and Cache Control
This article explains the PHP header() function, its syntax, parameters, and common use cases such as page redirection, setting HTTP response headers, status codes, preventing caching, and enabling file downloads, with clear code examples for each scenario.
In PHP, the header() function is a crucial tool for performing page redirects and setting HTTP response header information.
The basic syntax of header() 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 with the same name; default is true.
$http_response_code (optional): the HTTP status code to set; must be a valid code.
1. Page Redirection
The header() function can redirect users 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 for JSON output:
header("Content-Type: application/json");3. Setting HTTP Status Codes
Use header() to define the response status, for example a 404 Not Found:
header("HTTP/1.1 404 Not Found");4. Preventing Page Caching
To stop browsers from caching a page, send cache‑control headers:
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");5. Enabling File Downloads
By setting Content-Disposition to attachment , you can force 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 versatile for redirects, header manipulation, status codes, cache control, and file downloads. It must be called before any output is sent; otherwise, PHP will raise an error. After sending headers, it is advisable to terminate the script with exit to avoid unintended output.
Understanding and correctly using header() enables developers to manage HTTP responses effectively in PHP web applications.
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.