In PHP, the header() function is an essential tool for sending raw HTTP headers to the client. It allows you to control caching, redirection, content types, and more. Meanwhile, the headers_list() function helps inspect all the HTTP headers that have already been set, which is extremely helpful for debugging and understanding how your script behaves.
This article will explain how to use header() and headers_list() in detail, with code examples to help you get the hang of their usage.
The basic syntax of the header() function is:
header(string $header, bool $replace = true, int $response_code = 0): void
$header: The header content to be sent, such as Content-Type: application/json.
$replace: Whether to replace a previous header with the same name. Defaults to true.
$response_code: Optional. Sets the HTTP response status code.
Common use cases include:
header('Location: https://m66.net/new-page.php');
exit;
This line will redirect the browser to https://m66.net/new-page.php.
header('Content-Type: application/json');
echo json_encode(['status' => 'ok']);
This tells the client that the content to follow is in JSON format.
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');
These headers disable caching, ensuring the client always fetches the latest version.
Sometimes you might call header() multiple times in a script. So how can you check which headers have actually been set? That’s where headers_list() comes in handy.
<?php
header('Content-Type: text/plain');
header('X-Custom-Header: CustomValue');
header('Location: https://m66.net/redirected');
<p>$headers = headers_list();</p>
<p>echo "Currently set HTTP headers:\n";<br>
foreach ($headers as $h) {<br>
echo $h . "\n";<br>
}<br>
?><br>
Explanation:
We set three headers.
Then we use headers_list() to retrieve all currently set headers and print them line by line.
When you run this script, the output will look something like:
Content-Type: text/plain
X-Custom-Header: CustomValue
Location: https://m66.net/redirected
Please note:
If any output (like using echo) has already been sent before calling header(), it will cause a “header already sent” error.
Therefore, always set headers before sending any output.
Related Tags:
header