When you open a Web page in your browser, apart from the web page, you're also bringing back something called an HTTP HEADER. It is some additional information, such as a type of programme making the request, date requested, should it be displayed as an HTML document, how long the document is, and a lot more besides.

PHP headers can perform certain things, some of them are listed below:

  • Tell browser not to cache the pages.
  • Content-Type declaration
  • Page Redirection

Redirecting Browser

You can redirect your user to some other page.

  header("Location: http://www.example.com/");

The following command will redirect the browser window to the given location as soon as the command is executed.

Please note that Location starts with capital L, some browsers might not redirect if small l is used.

Even though you redirected the user successfully, yet this is not the proper way to do it. The above command does not generate the 301 response which means the target page will lose a hit count and SEO ranking. To avoid that, you have to add an additional header.

  header("HTTP/1.1 301 Moved Permanently");
  header("Location: http://www.example.com/");

Furthermore, you can add some redirection interval by using the following code:

  header("Refresh: 5; url=http://www.example.com"); //will redirect after 5 seconds

Do not cache pages

You can prevent the browser to cache pages by using the following code:

  //Date in the past, tells the browser that the cache has expired
  header("Expires: Mon, 20 Feb 2005 20:12:03 GMT");
  /* The following tell the browser that the last modification is right not so it must load the page again */
  header("Last-Modified: ". gmdate("D, d M Y H:i:s"). "GMT");
  header("Pragma: no-cache");

The above code will let the browser load the page fresh from the server every time it is called. The reason is simple; we tell the browser that the content just expired and it was just last modified too. Furthermore, we also tell it Pragma: no-cache to make sure it gets a fresh server copy each time.

Content Types

Other than HTML, you can also generate different types of data, e.g., you can parse an image, zip, XML, JSON, etc. If you do that then, you need to tell to the browser that content type is something else.

  //Browser will deal page as PDF
  header ( "Content-type: application/pdf" );
  //myPDF.pdf will called
  header ( "Content-Disposition: attachment; filename=myPDF.pdf' " );

Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram