The PHP header function allows us to send unformatted headers to the client (robot, browser…). It is a way to force such sending before the headers are read from the page itself.
Here is the sintax extracted from de official website:
header ( string [, bool [, int ]] )
In the following examples we will see the most common use of the PHP header() function.
In the following example we are going to make a redirect 301 without using the apache configuration or a .htaccess, the code is the following:
<?php // Redirect 301 Moved Permanently header("Location: /myurl.html",TRUE,301); ?>
In the upper lines you will see that I do the redirect 301 of the current page to ‘/myurl.html’ with true value.
But you can also use .htaccess to make a redirect 301… the result is the same.
<?php header("Expires: Tue, 13 Jan 2005 16:00:00 GMT"); //always put the date in the past tense header("Pragma: no-cache"); header("Cache-Control: no-cache"); ?>
If the page browsed does not exist, we can force the visit to end in the typical 404 page, here the code to be put in our PHP:
<?php header("HTTP/1.0 404 Not Found"); header ('Location: /404.html'); ?>
In this case we will force the download of a ZIP file:
header("Content-Description: File Transfer"); header("Content-Type: application/zip"); header("Content-Disposition: attachment; filename=filename.zip;"); //Size of the file in bytes header("Content-Length: Size of the file en bytes"); header("Content-Transfer-Encoding: binary"); readfile("filename.zip"); exit;
header("X-Robots-Tag: noindex, nofollow", true);
In this line we are showing the robot not to index or follow the links on the page. We can change the parameters of ‘noindex’ and ‘nofollow’ for any of the directives that it is put for the robots.
I hope that this post will be useful to know more about the PHP header() function.