How to work with header function in PHP – Quick Tips

Author: | Posted in PHP, Quick Tips No comments

Definition:

  1. The header() function sends a raw HTTP header to a client.
  2. It is important to notice that header() must be called before any actual output is sent.
  3. It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called

Syntax:

header(string,replace,http_response_code)
Parameter Description
String Required. Specifies the header string to send
replace Optional. Indicates whether the header should replace previous or add a second header. Default is TRUE (will replace). FALSE (allows multiple headers of the same type)
http_response_code Optional. Forces the HTTP response code to the specified value.

 

 

 

 

 

Using server-side scripting for redirection:

An HTTP response with the 301 “moved permanently” redirect looks like this:

HTTP/1.1 301 Moved Permanently 
Location: http://www.example.org/ 
Content-Type: text/html 
Content-Length: 174 
<html> 
<head> 
<title>Moved</title> 
</head> 
<body> 
<h1>Moved</h1> 
<p>This page has moved to <a href="http://www.example.org/">http://www.example.org/</a>.</p>
</body>
</html>
It redirect to mentioned url permanently
header(‘HTTP/1.1 301 Moved Permanently’);
header(‘Location: http://www.example.com/’);
exit();

Example-1:

There is used a header function for prevent caching.

<?php
// Date in the past
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Cache-Control: no-cache");
header("Pragma: no-cache");
?>

Example-2:

There is used a header function for content disposition (prompted a save dialogue for pdf file)

<?php
header("Content-type:application/pdf");
// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");
?>

Example-3:

There is used a header function for URL redirection. When the header redirects the page, the URL at the address bar is not changed

<?php
header('Location: http://myhost.com/mypage.php');
?>

Example-4:

It is used to refresh pager after some time of interval.

<?php 
    // for refreshing a page
    $sec = 10;
    header("Refresh: $sec;");
?>

Example-5:

You can use HTTP’s etags and last modified dates to ensure that you’re not sending the browser data it already has cached.

<?php 
$last_modified_time = filemtime($file); 
$etag = md5_file($file); 
header("Last-Modified: ".gmdate("D, d M Y H:i:s", $last_modified_time)." GMT"); 
header("Etag: $etag"); 
if (@strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) == $last_modified_time || 
    trim($_SERVER['HTTP_IF_NONE_MATCH']) == $etag) { 
    header("HTTP/1.1 304 Not Modified"); 
    exit; 
} 
?>