Aims:
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' } ?>
Suppose the client requests www.cs.ucc.ie/mywebsite/mywebpage.html
:
Suppose the client requests www.cs.ucc.ie/mywbsite/mywbpage.html
.
Oops! Typo!
mywebpage.html
is stored in
a folder called mynewwebsite
and not in mywebsite
mynewwebsite/mywebpage.html
).htaccess
file
Redirect 301 /mywebsite/mywebpage.html
http://www.cs.ucc.ie/mynewwebsite/mywebpage.html
Suppose the client requests the old URL,
www.cs.ucc.ie/mywebsite/mywebpage.html
:
header
functionheader
function allows us to change the status and
response header lines that we send back to the clientheader
before any of the (X)HTML is generated*
header('Location: http://www.cs.ucc.ie/mywebsite/anotherscript.php');
This will send a 302 status code and hence redirects the client to another script
(*unless PHP's output buffering is enabled, which it is not in our installation)
<?php $users_input = $_GET['capital']; if ($users_input == 'F') { header('Location: correct.html'); } else { header('Location: incorrect.html'); } ?>
capital.php
<?php session_start(); $_SESSION['users_input'] = $_GET['capital']; if ($_SESSION['users_input'] == 'F') { header('Location: correct.php'); } else { header('Location: incorrect.php'); } ?>
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!'; } } ?>