PHP header function is to send a raw HTTP header to the client. The raw header contains the request and other metadata. It helps to set content type, caching, location and similar data.
The HTTP header is to pass additional details with an HTTP request. It contains the details in the form of key: value pairs.
To redirect to a URL:
<?php
header("Location: https://phppot.com");
exit;
?>
To redirect after X seconds:
<?php
header( "refresh:5;url=target.php" );
echo 'You will be redirected in 5 secs. If not, click <a href="target.php">here</a>.';
?>
The header() is a built-in PHP function existing even in earlier versions. But as of 5.1.2, it stops sending more than one header at a time to avoid the header injection attacks.
PHP header must be called before sending any output to the browser. Otherwise, it will cause a “Cannot modify header information ... header already sent ...”
error.
These are the items not allowed before calling PHP headers.
The PHP header function has three parameters. It uses the following syntax which shows the three parameters of this function. This function returns (void) no value.
header(String $header, bool $replace=true, int $response_code=0);
It contains a string defining HTTP status code. It defines the header properties like content type, location and more.
The header location redirects users to the target URI and returns the 302 status code to the client.
It is to replace the header property already defined. This is an optional parameter having boolean true as a default value. It overrides the defined header settings by default. We can turn the default behavior off by setting false to this parameter.
<?php
header('WWW-Authenticate: Negotiate');
echo ('header WWW-Authenticate is set to Negotiate \n');
header('WWW-Authenticate: NTLM', false);
echo ('header WWW-Authenticate is changed to NTLM');
?>
This is also an optional parameter containing the default integer value 0. This is to set the HTTP response code. It is applicable if and only if the header is not empty.
The list of items shows some of the uses of the PHP header function. This article includes examples to explain the uses of the header() function.
The usage of the PHP header location setting is as follows. It starts with the Location keyword followed by the target URI.
The header function executes page redirect in PHP on the server-side. The below code uses the PHP exit statement. It stops executing code follows after the redirect.
<?php
// PHP header with Location to redirect
header("Location: https://phppot.com");
exit;
?>
It accepts both relative and absolute URI for the redirect.
Some of the old clients accept absolute URI. The below code forms absolute URI dynamically to set the header location. It uses the $_SERVER globals $_SERVER[‘PHP_SELF’], $_SERVER[‘HTTP_HOST’] and the dirname().
<?php
$subDirectory = rtrim(dirname($_SERVER['PHP_SELF']), "/\\");
$fileName = "example.php";
header("Location: http://" . $_SERVER['HTTP_HOST'] . "/" . $subDirectory . "/" . $fileName);
?>
The above code finds the subdirectory name of the file. Then, it trims the unnecessary slashes at the end of the string.
This PHP script sets content type and content-disposition to force to download. It outputs a document in the specified content type.
It set the application/pdf to output a PDF file to the browser. It sets the source and destination to read and prepare the output document.
This code will display a dialog to save the PDF document generated. We have used jsPDF save() method to show the download PDF into the browser.
<?php
//Set header content type as PDF
header("Content-type:application/pdf");
// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename=output.pdf");
// The source file to read content
readfile("source.pdf");
?>
If you want to send response as a JSON, in the above change “Content-type” to application/json.
Below code sets PHP header() to prevent the browser from caching the page content. By defining these header settings, it overrides the default caching mechanism.
It uses HTTP 1.1 caching options to set Cache-Control. It puts the values no-cache, must-revalidate tp this header.
It sets Expires header with a past date and lets the client know that there is no more cached content. So, it will send a HTTP request to the server to read the content.
<?php
// HTTP/1.1 caching options
header("Cache-Control: no-cache, must-revalidate");
// Past date time as the expiry
header("Expires: Mon, 2 Jul 1963 03:00:00 GMT");
?>
<!-- Page template HTML begins -->
The below functions are related to the PHP header function. Let us see the purposes of these functions with a simple example.
This function ensures that the header is already sent to the client. It will return boolean true or false.
It accepts optional $filename and $linenumber params passed by reference. It will be used later and no need to assign them before the header_sent() invoke.
PHP sets the source filename to the $filename parameter. Also, it sets the second parameter with the line number where the output begins.
This function avoids the occurrence of header-related fatal errors. The below example prints explicit error messages by interpolating variables $filename and $linenum.
<?php
// Check if header sent already
if (!headers_sent()) {
header('Location: http://yourdomain.com/');
exit;
}
// Set optional $filename of the source PHP and
// $linenum where output starts
if (!headers_sent($filename, $linenum)) {
header('Location: http://yourdomain.com/');
exit;
} else {
// prints error message to avoid fatal errors
echo "Headers already sent in $filename on line $linenum";
exit;
}
?>
The purpose of this function is understandable by its name. It is for removing the header that is already set.
It accepts the name of the header as its parameter. Its value is case insensitive.
<?php
//Set header content type as JSON
header("Content-type:application/json");
header_remove("content-type");
?>
This PHP function returns the list of headers sent already or the headers set to be sent. It returns output in the form of PHP array.
This code set cookies and PHP headers. It sets member random id into PHP cookie index and sets the content type as plain text.
<?php
//set cookie to store random number as member_id
setcookie('member_id', rand(10000, 99999));
// custom header
header("X-Sample: Example");
// set content-type as plain text
header('Content-type: text/plain');
/* Prints the set headers */
var_dump(headers_list());
?>
This program prints the header list as follows.
array(4) {
[0] = >
string(24) "X-Powered-By: PHP/7.4.21"
[1] = >
string(27) "Set-Cookie: member_id=87530"
[2] = >
string(17) "X-Sample: Example"
[3] = >
string(38) "Content-type: text/plain;charset=UTF-8"
}
The header_register_callback() function is to register a no-argument callback function. PHP invokes the callback function after it is ready to send all the headers.
header_register_callback(callable $callbackFunction);
Yes, we have seen an elaborate article on PHP headers. I hope that it covers all the direct and related points about this function.
It gives a variety of examples in PHP headers to set content type, caching and more. Also, it covers the related functions like header_list(), header_remove(), etc.
If you have comments or suggestions, share them in the comments section.
ôh what generous women you are vincy , thank you every time every day thank you forever vincy this article come just the time i need to it , it’s very important so clear it give me help
Welcome Redouane Sehbani.
As always, this is brilliant. Thank you so much for creating these extraordinarily useful tutorials.
Best regards
Rob
Thank you Rob for your support for me.
Thanks for enlightening me on php Headers
Welcome Simon.