Updated March 31, 2023
Introduction to PHP header()
PHP header is an inbuilt function that is used to send a raw HTTP header to the client and it is mandatory that they actually manipulate the information which is sent to the client or browser before any original output can be sent. A raw request (like an HTTP request) is sent to the browser or the client before HTML, XML, JSON or any other output has been sent. HTTP headers contain required necessary information of the object which is sent in the message body more accurately on the request and its response.
Syntax and Parameter
Below are the syntax and parameter:
Syntax
void header( $header_name, $replace_param = TRUE, $http_response_code )
header_name() here is a mandatory field and sends the header string to be sent
replace parameter: It is an optional boolean type field and shows if the present header should replace a previous similar-looking header or should add a new header which is of the same type. By default its value is TRUE and by this, it replaces the header unless given FALSE which allows giving multiple headers but the condition is that it should have the same type.
Code:
<?php
header('WWW-Authenticate: Negotiate');
echo ('header has been changed to WWW-Authenticate: Negotiate');
echo "\n";
header('WWW-Authenticate: NTLM', false);
echo ('header has been changed to WWW-Authenticate: NTLM');
?>
Output:
http_response_code: It is also an optional field which forces the HTTP response received to the given value. Available in versions PHP 4.3 and higher.
The header() here is used to send a raw HTTP header. This header hence must be called before any other output is been sent either by usual HTML tags, blank lines or from PHP. A few common mistakes are to read the code with include, access or any other require functions, having spaces or empty lines which are output before calling the header(). This problem also exists when we are using an individual PHP or an HTML file.
Return Values: header() function does not return any value. In header calls, there are 2 types: The first one starts with the string “HTTP/” (case insignificant) which is used to find out the HTTP status code to send.
Examples to Implement PHP header()
Below are the examples:
Example #1
Code:
<?php
header("HTTP Error 404: Not Found");
echo ('Header been changed to HTTP Error 404: Not Found');
?>
Output:
Explanation: The second type is the Location header which sends the header back to a web browser and also returns back a REDIRECT status code to the browser until and unless status codes 201 or 3xx have been already sent.
Example #2
Code:
<?php
header("Location: http://www.example_site.com/");/* This is to redirect the browser */
echo("Browser successfully redirected to http://www.example_site.com/");
exit;
?>
Output:
Example #3
Code:
<?php
// To output a PDF header
header('Content-Type: application/pdf');
// Let the filename be called file.pdf
header('Content-Disposition: attachment; filename="file.pdf"');
// The source of PDF can be found in oldfile.pdf
readfile('oldfile.pdf');
?>
Output:
Explanation: In this example, we are prompting the user to save the generated PDF file being sent to them. For this purpose, we use the Content-Disposition header to give a required file name and to force the web browser to show the save dialog.
Example #4
Code:
<?php
header("Cache-Control: no-cache, hence should-revalidate");
header("Expires: Sun, 25 Jun 1999 04:00:00 GMT");
// Providing some random date in the past
echo('Displaying header information: Cache-Control: no-cache, hence should-revalidate' );
?>
Output:
Explanation: In this example, we are using certain proxies and clients to disable the caching process of PHP. This is because PHP often creates dynamic content that should not be cached by the web browser or any other proxy caches which come in between server and browser.
Sometimes it may happen that the pages will not be cached even if the above said lines and headers are not incorporated in the PHP code. This is because a lot of options are available which a user can set for his browser that actually changes its default set caching behavior. Hence by using the above-mentioned headers we will be able to override all the settings which may cause the output of PHP script to be cached.
There is also another configuration setting called the session.cache_limiter which generates the correct cache-related headers automatically when different sessions are being used.
Example #5
Code:
<?php
// PHP program to describes header function
// Set a past date
header("Expires: Sun, 25 Jul 1997 06:02:34 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
?>
<html>
<body>
<p>Hello World!</p>
<!-- PHP program to display
header list -->
<?php
print_r(headers_list());
?>
</body>
</html>
Output:
Explanation: The above-given example is used to prevent caching which sends the header information to override the browser setting so that it does not cache it. We are using the header() function multiple times in this example as only one header is allowed to send at one time. This prevents something called header injection attacks.
Example #6
Code:
<?php
header( "refresh:10;url=example.php" );
echo 'You will be redirected in 10 seconds. If not please click <a href="example.php">here</a>.';
?>
Output:
Explanation: This example above is used to redirect the user and to inform him that he will be redirected.
Example #7
Code:
<?php
// Test image.
$t1 = 'https://cdn.educba.com/test/image.png';
// Headers being sent by the client
$headers = apache_request_headers();
// To check if the cache is being validated by the client and whether it is current
if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == ftime($t1))) {
// We shall respond with '304 Not Modified' if the client cache is current
header('Last-Modified: '.gmdate('D, d M Y H:i:s', ftime($t1)).' GMT', true, 304);
echo(‘’);
} else {
// We shall display '200 OK' by outputting the image if it is not cached or outdated cache
header('Last-Modified: '.gmdate('D, d M Y H:i:s', ftime($t1)).' GMT', true, 200);
header('Content-Length: '.filesize($t1));
header('Content-Type: image/png');
print file_get_contents($t1);
}
?>
Output:
Explanation: In the above example, we are using PHP headers to cache an image being sent and hence bandwidth can be saved by doing this. First, we take the image and check if it is already cached, this by setting the cache to IS current. If it is not current then we are caching the same and sending the image in the output.
Advantages of using header function in PHP
- PHP headers are very essential in redirecting the URI string also to display the appropriate message such as “404 Not Found Error”.
- PHP headers can be used to tell the web browser what type the response is, and the content type.
- The redirect script which will be used at the beginning helps in saving time of execution and bandwidth.
Conclusion
As seen above, the header forms a major part of each document as it tells the web browser what kind of document it is so that the browser reads it correctly. Hence it is responsible for providing raw HTTP headers to browsers and also to redirect the same to different proper locations.
Recommended Articles
This is a guide to PHP header(). Here we discuss an introduction to PHP header() along with appropriate Syntax, and top 7 examples to implement with proper codes and outputs. You can also go through our other related articles to learn more –