PHP header() Function
PHP header() sends a raw HTTP header to the browser. Headers are small instructions that go before the actual page content.
Using header() you can redirect a user to another page, change the content type (like JSON), set a status code or force a file download.
Syntax
header(string $header, bool $replace = true, int $response_code = 0): void
Parameters
| Parameter | Description |
|---|---|
| header | Required. The header string, for example “Location: https://example.com” |
| replace | Optional. true (default) replaces a previous similar header. false adds a second header of same type |
| response_code | Optional. Forces the HTTP response code, like 301 or 404 |
Common headers
| Header | Use |
|---|---|
| Location: url | Redirect to another URL |
| Content-Type: application/json | Tell browser that response is JSON |
| Content-Disposition: attachment; filename=”file.txt” | Download the response as a file |
| Cache-Control: no-cache | Ask browser not to cache the page |
Examples
Example #1: Redirect to another page
This code sends the user to the Tutorials Class homepage. We call exit after the redirect so rest of the script does not run.
<?php
header("Location: https://tutorialsclass.com/");
exit;
?>
Result: The browser opens https://tutorialsclass.com/ automatically.
Example #2: Send JSON response
APIs use the Content-Type header, so the client knows it is JSON data.
<?php
header("Content-Type: application/json");
echo json_encode(["name" => "Robin", "city" => "Delhi"]);
?>
Output:
{“name”:”Robin”,”city”:”Delhi”}
Example #3: Permanent redirect (301)
Use the third parameter when you move a page forever. Search engines understand 301 as a permanent move.
<?php
header("Location: https://tutorialsclass.com/new-page/", true, 301);
exit;
?>
Example #4: Download a file
<?php
header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=\"notes.txt\"");
echo "Hello from Tutorials Class";
?>
Result: The browser downloads a file named notes.txt with the text inside.
Headers already sent error
This is the most common problem with header(). It happens when the script prints something before header().
<?php
echo "Hello";
header("Location: https://tutorialsclass.com/");
?>
Output:
Hello
Warning: Cannot modify header information – headers already sent by (output started at /path/index.php:2) in /path/index.php on line 3
How to fix it:
- Call header() before any echo, print or HTML.
- Remove blank lines or spaces before the opening
<?phptag. - Save your PHP file as UTF-8 without BOM.
- Use
ob_start()at the top if you cannot change the order.
Summary
- header() sends a raw HTTP header to the browser.
- It must run before any output.
- Call exit after a Location redirect.
- Use the third parameter to set a status code like 301.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |