Thursday, September 2, 2010

PHP Headers

  • HTTP is the protocol (the set of 'rules') for transferring data (e.g. HTML in web pages, pictures, files) between web servers and client browsers, and usually takes place on port80. This is where the 'http://' in website URLs comes from. 
  • Headers can be separated into two broad types: Request the headers that your browser sends to the server when you request a file, and Response headers that the server sends to the browser when it serves the file.
PHP header(): The Basics
  • Using this function, you can make your scripts send headers of your choosing to the browser, and create some very useful and dynamic results. However, the first thing you need to know about the header() function is that you have to use it before PHP has sent any output (and therefore its default headers).























Redirecting with the Refresh header

  • While you can sometimes get away with supplying a relative URL for the value, according to the HTTP specification, you should really use an absolute URL.
  • One mistake that is easy to make with the Location header is not calling exit directly afterwards (you may not always want to do this, but usually you do). The reason this is a mistake is that the PHP code of the page continues to execute even though the user has gone to a new location. In the best case, this uses system resources unnecessarily. In the worst case, you may perform tasks that you never meant to.

Example :
header('Refresh:10;url=http://www.mysite.com/otherpage.php');
echo'Youwillberedirectedin10seconds';

  • The Refresh redirects users like the Location header does, but you can add a delay before the user is redirected. For example, the following code would redirect the user to a new page after displaying the current one for 10 seconds



Serving different types of files and generating dynamic content using the Content-Type header:



The Content-Type header tells the browser what type of data the server is about to send. Using this header, you can have your PHP scripts output anything from plaintext files to images or zip files. The table below lists frequently-used MIME types:

You can do several interesting things with this. For example, perhaps you want to send the user a pre-formatted text file rather than HTML:


Example : header('content-Type:text/plain');



Or perhaps you'd like to prompt the user to download the file, rather than viewing it in the browser. With the help of the Content-Dispositionheader, it's easy to do, and you can even suggest a file name for the user to use:

Example:
header('Content-Type:application/octet-stream');
header('Content-Disposition: attachment; '.'filename="plain_text_file.txt"'); 

1 comment:

  1. Thanks A Lord For Publish In Your Blog, This Is A Great Things To Learned Many Information. Keep Posting Many Blogs Like This.
    Web portal development company in chennai, Web portal development services in chennai

    ReplyDelete