Craig Francis


PHP Redirect

If you want to redirect a user onto a new page, then you can use this function...

function redirect($goto) {

if (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') {
if (preg_match('/^http:\/\//', $goto)) {
header('Refresh: 0; URL=' . $goto);
exit('<p><a href="' . htmlentities($goto) . '">Loading...</a></p>');
}
}

header('Location: ' . $goto);
exit('<p>Goto <a href="' . htmlentities($goto) . '">next page</a></p>');

}

And for an example of its usage...

redirect('http://www.domain.com/contact/thankYou/');

This function takes into account of a bug in IE6 - if a form submits to a page using HTTPS, and that page then redirects the user onto a standard HTTP connection, then IE6 complains that the data is being submitted over an insecure connection, and asks the user if they want to continue.

You will also notice the exit() calls... I have seen quite a few developers call the header('Location'), and forget that the PHP script continues to execute. This is possibly because they don't see the output, but for an added bonus, we also use that exit() call to provide a link for the really old browsers that do not understand the 'Location' header.

Please note, you should not really use relative links (../) in a 'Location' header, mainly because it's not following the specification. Although most browsers can work it out, the HTTP specification asks for an absolute URI.

Any feedback would be greatly appreciated. If you would like to use this code, please read the licence it is released under.