Backend Development 2 min read
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
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 lengthWritten 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
Rate this article
Was this worth your time?
Discussion
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.