In this tutorial you will learn about the PHP Headers and its application with practical example.
In PHP HTTP HEADER are some extra information passed to browser such as type of program making the request, date requested, should it be displayed as a HTML document, how long the document is, and a lot more besides. One of the things HTTP HEADER also does is to give status information.
Some of the basic uses of HTTP HEADER are:
- Redirect Page
- Send content types
- Tell the browser to not cache some pages
Note:- Headers are preferred to be the first one to be sent to the browser. That is only when it can work properly.
Location Header
This will send a new location to the browser and it will immediately redirect.
1 2 3 |
<?php header("Location: http://w3school.in"); ?> |
It’s recommended to put a full url there, however almost all browsers support relative urls.
Content Type Header
You can also control the content type using the header that the browser will treat the document as:
1 2 3 |
<?php header("Content-Type: text/css"); ?> |
You can also force the browser to display the download prompt and have a recommended file name for the download.
1 2 3 4 |
<?php header("Content-Type: image/jpeg"); header("Content-Disposition: attachment; filename=file.jpg"); ?> |
You can also send specific errors to the browser using the header function. It’s important to remember the different error messages and what they mean.
1 2 3 |
<?php header("HTTP/1.0 404 Not Found"); ?> |
You can prevent the browser to cache pages by using the following code:
1 2 3 4 5 6 7 8 9 10 11 |
<?php //Date in the past, tells the browser that the cache has expired header("Expires: Sun, 25 Nov 2012 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.