Redirecting the User

You want to redirect the user to a new location.

Use header() to modify the HTTP response header sent by the server. The header information must be sent to the browser before any HTML and text. It's important that the header() function is executed first.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
 header("Location: http://www.cnn.com");
 exit;
?>
</p>
</body>
</html>

View the effect

You need to enable output buffering if you want to display HTML first.


<?php
// Enable output buffering. No output is sent from the script
// (other than headers). It is saved in an internal buffer
ob_start();
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>Redirecting the User</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
 header("Location: http://www.cnn.com");
 exit;
?>
</p>
</body>
</html>

View the effect

This is another example.


<?php
// Enable output buffering. No output is sent from the script
// (other than headers). It is saved in an internal buffer
ob_start();
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>Redirecting the User</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php

function display_form() {
echo <<<HTML
Which search engine would you like to use?
<form action = "$_SERVER[SCRIPT_NAME]" method="post">
<select name="new_url">
	<option VALUE="" /></option>
	<option value="http://www.google.com/" />Google</option>
	<option value="http://www.yahoo.com" />Yahoo</option>
	<option value="http://www.msn.com" />MSN</option>
</select>
<input type="submit" value="Go">
</form>
HTML;
}

if (isset($_POST['new_url'])) {
	header("Location: $_POST[new_url]");
}
else {
	display_form();
}

?>
</p>
</body>
</html>

View the effect


Forms | Introduction | Creating a Form | Superglobals | Processing Form Input | Required Fields | Numbers | Drop-Down Menus | Radio Buttons | Checkboxes | Periods in Their Names | Preventing Cross-Site Scripting | Stripping out Slashes | Redirecting the User | Server Information | Determining Browser Type | Sticky Forms
© 2008: Hann So
email: hso@voyager.deanza.edu