PHP 5 Headers
When you open a Web page in your browser, apart from the web page you're also bringing back something called a HTTP HEADER. This is some additional information, such as type of programme making the request, date requested, should it be displayed as a 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 to not cache the pages.
- Content Type declaration
- Page Redirection
You can redirect your user to some other page.
<?php 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 loose a hit count and SEO ranking. To avoid that, you have to add additional header.
<?php 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:
<?php 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:
<?php //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"); //HTTP/1.0 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.
Other than HTML, you can also generate different types of data, e.g., you can parse an image, zip, psd etc. If you do that then, you need to tell to browser that content type is something else.
<?php //Browser will deal page as PDF header ( "Content-type: application/pdf" ); //myPDF.pdf will called header ( "Content-Disposition: attachment; filename=myPDF.pdf' " ); ?>
|« Previous Chapter |
PHP Form Validation
|Next Chapter » |
PHP File Handling