header redirect

The header() function is used to send a raw HTTP header and must be called before any output is sent, either by normal HTML tags, blank lines in a file, or from PHP.

 

This examples gives the standard redirect to the specified URL after the Location keyword, both enclosed within quotes:

<?php

	header("Location: https://www.example.com/"); /* Redirect browser */

	/* Make sure that code below does not get executed when we redirect. */

	exit;

?>

 

A slight variation to redirect after a specified time using the refresh keyword with a chosen delay time and URL:

 

<?php header('refresh:5;url=/'); ?>

 

 

Or the sleep() function could be prior to the header() redirect function.

 

<?php

sleep(2);

header('location:/');

?>

 

 

Some other header() function examples:

 

Prevent page caching

<?php
//	Date in the past
	header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
	header( 'Cache-Control: no-store, no-cache, must-revalidate' ); 
	header( 'Cache-Control: post-check=0, pre-check=0', false ); 
	header( 'Pragma: no-cache' )
?>

 

Prompt user to download content.

(Content-Disposition header is used to supply a recommended filename and force the browser to display the save dialog box):

<?php
// We'll be outputting a PDF
header('Content-Type: application/pdf');

// It will be called downloaded.pdf
header('Content-Disposition: attachment; filename="downloaded.pdf"');

// The PDF source is in original.pdf
readfile('original.pdf');
?>

 

Basic HTTP Authentication example

<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
    header('WWW-Authenticate: Basic realm="My Realm"');
    header('HTTP/1.0 401 Unauthorized');
    echo 'Text to send if user hits Cancel button';
    exit;
} else {
    echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
    echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>

Leave a Reply