Share via:

HTTP Location Header

The location header is sent when performing permenant (301) and temporary (302) redirects. In PHP, we can send a Location header using the header function.

501 views

Edited: 2018-01-27 12:40

The HTTP Location header tells the browser to load another page, often used when performing 301 redirects. Usually a HTTP status code, such as the 303 See Other, is also sent when a location header is used.

The HTTP location header can be sent in response to any request that matches content which has been moved. The browser should automatically pass on the request to the location indicated in this header.

While a relative path might work in some clients, it is recommended to use absolute path with the location header.

$protocol = $_SERVER["SERVER_PROTOCOL"];
 // Determine the protocol
if (($protocol != 'HTTP/1.1') && ($protocol != 'HTTP/1.0')) {
  $protocol = 'HTTP/1.0';
}
 // Send the Headers
header($protocol . ' 303 See Other');
header('Location: http://beamtic.com/other-page');

Sending headers in PHP

When using the header function, it is a good idea to dynamically determine the protocol in one place, so you will not have to edit all the places the headers are sent, in case you later change the protocol.

$protocol = $_SERVER["SERVER_PROTOCOL"];
 // Determine the protocol
if (($protocol != 'HTTP/1.1') && ($protocol != 'HTTP/1.0')) {
  $protocol = 'HTTP/1.0';
}

To perform a redirect in PHP, we can use the header function. Assuming we are redirecting to /other-page from the current requested page, we can do like below:

header($protocol . ' 303 See Other');
header('Location: http://beamtic.com/other-page');

Note. Header's should always be sent before any output, such as that produced by echo, print, or by exiting PHP with "?>", otherwise you might get "headers already sent" errors.

Comments