Master PHP’s header() Function: Redirects, Headers, and Advanced Uses
This article provides a comprehensive guide to PHP's header() function, covering its syntax, parameters, and practical code examples for page redirection, setting HTTP response headers, status codes, cache control, and file downloads, helping developers use it effectively.
In PHP, the header() function is essential for page redirects and setting HTTP response headers. This article explains its usage and provides code examples.
Basic syntax of header()
header(string $header, bool $replace = true, int $http_response_code = 0): bool $header(required): the HTTP header string to send, e.g., "Content-Type: text/html;charset=utf-8". $replace (optional): whether to replace a previous header of the same name; true by default. $http_response_code (optional): the HTTP status code to set.
Common scenarios and code examples
Page redirection
The header() function can redirect users to a specified URL.
header("Location: http://www.example.com");
exit;Setting HTTP response headers
Use header() to set headers such as Content-Type or Content-Disposition.
header("Content-Type: application/json");Setting HTTP status codes
Set status codes like 200 for success or 404 for not found.
header("HTTP/1.1 404 Not Found");Preventing page caching
Send Cache-Control, Pragma, and Expires headers to disable caching.
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");File download
Set Content-Disposition to attachment and appropriate Content-Type and Content-Length 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");The header() function is versatile for redirects, header manipulation, status codes, cache control, and file downloads, and developers should understand its parameters to use it effectively.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
