HTTP Redirection

Derek Bridge

Department of Computer Science,
University College Cork

HTTP Redirection

Aims:

The way we've been doing things so far

Scripts can get longer and longer as we output different things depending on the user's input, e.g.:

<?php
$users_input = $_GET['capital'];
if ($users_input == 'F') 
{
   // Shed-load of XHTML and PHP to output something 
   // if the user's input == 'F'
}
else
{
   // Shed-load of XHTML and PHP to output something else
   // if the user's input != 'F'
}
?>

HTTP request and successful response

Suppose the client requests www.cs.ucc.ie/mywebsite/mywebpage.html: Diagram showing a successful HTTP GET request

HTTP request and unsuccessful response

Suppose the client requests www.cs.ucc.ie/mywbsite/mywbpage.html.
Oops! Typo! Diagram showing an unsuccessful HTTP GET request

HTTP request for a page that has moved

HTTP request for a page that has moved

Suppose the client requests the old URL, www.cs.ucc.ie/mywebsite/mywebpage.html: Diagram showing an HTTP GET request for a page 
 that has moved

PHP's header function

(*unless PHP's output buffering is enabled, which it is not in our installation)

PHP redirection example

<?php
$users_input = $_GET['capital'];
if ($users_input == 'F') 
{
	header('Location: correct.html');
}
else
{
	header('Location: incorrect.html');
}
?>

PHP redirection and sessions

PHP redirection and session example: capital.php

<?php
session_start();
$_SESSION['users_input'] = $_GET['capital'];
if ($_SESSION['users_input'] == 'F') 
{
	header('Location: correct.php');
}
else
{
	header('Location: incorrect.php');
}
?>

PHP redirection and session example: incorrect.php

<?php
   session_start();
?>
<?php echo '<?xml version="1.0" encoding="UTF-8"?>'; ?>
<!DOCTYPE html 
 PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
   <title>The capital of 'France'</title>
   <link rel="stylesheet" type="text/css" href="formlayout.css" />
</head>

<body>
 <p>
  <?php
   echo "No, that's not right. 
         {$_SESSION['users_input']} is not the capital of 'France'."
  ?>
 </p>
</body>
</html>

cookie_checker.php

Using redirection and a single script to check whether the client accepts cookies

<?php
if ( $_GET['sent_cookie'] != 'yes' )
{
   // Send the cookie...
   setcookie('test_cookie', 'test_value', time() + 60);
   // ...returning to this script
   header('Location: cookie_checker.php?sent_cookie=yes');
}
else
{
   // On your return, check whether the client sent the cookie back to you
   if ( isset($_COOKIE['test_cookie']) )
   {
      // Do whatever you want to do in the case where the client does have cookies enable, e.g.:
      echo 'You have cookies enabled!';
   }
   else
   {
      // Do whatever you want to do in the case where the client does not have cookies enabled, e.g.:
      echo 'You do not have cookies enabled!';
   }
}
?>