Master PHP’s header() Function: Redirects, HTTP Headers, and Caching Tricks

This article provides a comprehensive guide to PHP's header() function, covering its syntax, parameters, and practical examples for page redirection, setting HTTP response headers, controlling cache behavior, and enabling file downloads, while emphasizing proper usage before output.

php Courses
php Courses
php Courses
Master PHP’s header() Function: Redirects, HTTP Headers, and Caching Tricks

In PHP, the header() function is essential for page redirection and setting HTTP response headers. This article explains its usage with syntax and parameters.

Basic syntax:

header(string $header, bool $replace = true, int $http_response_code = 0): bool
$header

(required): The HTTP header string, e.g., "Content-Type: text/html;charset=utf-8". $replace (optional): Whether to replace a previous header of the same name. Default true. $http_response_code (optional): HTTP status code to send.

Common use cases with examples:

1. Page redirection

The function can redirect users to a specified URL.

header("Location: http://www.example.com");
exit;

2. Setting HTTP response headers

Set headers such as Content-Type.

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

3. Setting HTTP status codes

Send status codes like 404.

header("HTTP/1.1 404 Not Found");

4. Preventing page caching

Use Cache-Control, Pragma, and Expires headers.

header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");

5. File download

Set Content-Disposition and related headers to force download.

header("Content-Disposition: attachment; filename=example.pdf");
header("Content-Type: application/pdf");
header("Content-Length: " . filesize("example.pdf"));
readfile("example.pdf");

Summary

The header() function is versatile for redirects, header manipulation, caching control, and file downloads. It must be called before any output, and it is advisable to follow it with exit to stop script execution.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Backend DevelopmentcachingHTTPFile Downloadheader functionweb redirects
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.