Web development and examples of PHP, jQuery, HTML5, WordPress, MySQL & AMP


PHP header(): operation and redirect 301 with the Location header

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.

PHP header() sintax

Here is the sintax extracted from de official website:

  1. Usage: It must be put before any html tag or blank lines, otherwise it will give us an error similar to this: ‘Warning: Cannot modify header information – headers already sent by …‘.
  2. String (Required): String representing the header to be sent by the header function to the client.
  3. Bool: Boolean variable to replace headers of the same type sent previously, if you specify ‘false‘ the same headers sent previously will be kept.
  4. Int: Force the response code.

In the following examples we will see the most common use of the PHP header() function.

Example of redirect 301 with PHP header ‘Location

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:

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.

Avoid page caching with the ‘Expires’, ‘Pragma’ headings and ‘Cache-Control

Display 404 error with PHP header ‘STATUS

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:

Force File Download with PHP header()

In this case we will force the download of a ZIP file:

Index or no index urls with PHP header()

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.

Cookie Policy

This website uses cookies to provide you with the best user experience. If you continue to browsing you are consenting to the acceptance of these cookies and acceptance of our cookie policy, click the link for more information.

ACEPTAR
Aviso de cookies