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.
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 seconds5. 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 lengthSigned-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.
