What is the use of the header() function in PHP?
The header() function sends a raw HTTP header to the browser, before the page content. With headers you can give instructions to the browser.
Common uses of header():
- Redirect the user to another page (
Locationheader). - Tell the type of response, like JSON (
Content-Typeheader). - Force a file download (
Content-Dispositionheader). - Control browser cache (
Cache-Controlheader). - Set the HTTP status code, for example 404 or 301.
<?php
header("Content-Type: application/json");
echo json_encode(["status" => "ok"]);
?>
Output:
Tutorials Class - Output Window
{“status”:”ok”}
Note:
header() must be called before any output, even a blank space. Otherwise PHP shows the “headers already sent” warning. Full details and more examples are in PHP header() Function.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |