PHP header redirect function
10 March 2009
PHP headers can do anything from force download of a file, render the page as a different file format or redirect the page to another URL.
All PHP headers must be placed before anything is output onto the page.
We want to use the PHP code:
<?php
header ("Location: http://www.redirect.com");
exit;
?>
If a PHP header occurs after text has been output onto the page you will get a list of PHP header errors.
To escape any errors from being output onto the page you can put the @ symbol before any PHP function, but the page still won't redirect.
In this case we want to hide the errors from being displayed, and still redirect the page.
Page redirects can be carried out using javascript as well like this:
<script type="text/javascript">
window.location.href="http://www.redirect.com";
</script>
Again the flaw here is if the user has javascript turned off, which will result in the rest of the page being displayed.
The last result of redirect would be the HTML meta tag to refresh, with code like this:
<meta http-equiv="refresh" content="0;url=http://www.redirect.com" />
So all together we have 3 forms of page redirect and so I decided to make it into a function so that no errors will be displayed when redirecing and if the first method doesn't work then one of the other 2 methods hopefully will.
function redirect($url)
{
if (!headers_sent()) //If headers haven't yet been sent
{
@header('Location: '.$url); exit;
}
else //Headers have already been sent
{
echo '<script type="text/javascript">'; //Echo the javascript redirect code
echo 'window.location.href="'.$url.'";';
echo '</script>';
echo '<noscript>'; //If javascript is turned off this code will execute
echo '<meta http-equiv="refresh" content="0;url='.$url.'" />';
echo '</noscript>'; exit;
}
}
If this still doesn't work then you're doing something wrong!
http://www.peternichol.com/entry/trackback/46/
Please leave a comment using the form provided.






