7 Common Uses of PHP’s header() Function

This article outlines seven practical applications of PHP’s header() function, including page redirection, content‑type declaration, HTTP status codes, timed redirects, cache control, authentication prompts, and file download handling, providing code examples for each use case.

php Courses
php Courses
php Courses
7 Common Uses of PHP’s header() Function

This article introduces seven useful ways to employ PHP’s header() function.

1. Page redirection

header('Location:' . $url); // No space between Location and :

2. Declaring content‑type header('content-type:text/html;charset=utf-8'); 3. Returning HTTP response status code header('HTTP/1.1 404 Not Found'); 4. Timed redirect

header('Refresh: 10; url=http://www.baidu.com/'); // Redirect after 10 seconds

5. Controlling browser cache

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");

6. HTTP authentication

header('HTTP/1.1 401 Unauthorized');
header('WWW-Authenticate: Basic realm="Top Secret"');

7. File download

header('Content-Type: application/octet-stream'); // Set content type
header('Content-Disposition: attachment; filename="example.zip"'); // Set as attachment
header('Content-Transfer-Encoding: binary'); // Set transfer encoding
header('Content-Length: ' . filesize('example.zip')); // Set content length
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.

BackendHTTPheader
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.