Something every web developer has to do a lot is redirecting your web page to another location. For PHP developers it usually looks like this:
<?php header('Location: http://www.mylocation.com'); ?>
This works well enough as long as headers have not been sent. A common mistake for PHP developers is to use ob_start() to put all content into the output buffer. This can be useful for other functions such as compression, but it’s not a good habit to get into just to compensate for sloppy code. Here is a simple little function that can help redirect using multiple methods.
The Code
The part I always like to start out with
:
<?php function location($url, $time = 0) { if (!headers_sent() && $time == 0) { header('Location: ' . htmlspecialchars($url)); die(); } else { echo "<script type='text/javascript'>setTimeout('window.location = \'" . htmlspecialchars($url) . "\'', " . ($time * 1000) . ");</script> <noscript><meta http-equiv='refresh' content='" . $time . ";url=" . htmlspecialchars($url) . "' /></noscript> "; if ($time == 0) { die(); } } } ?>
This simple function detects to see if headers have already been sent. If they have it will output some javascript that will redirect the page and kills the script so that no more content is output. In case javascript is disabled on a certain browser (as it very well can be) there is a <noscript> tag to check for this and it will output a <meta tag that has the attribute of "http-equiv". This tells your browser to treat this tag as though it were an http header. The second aspect of this code is that you can set a timer. This is the amount of time in seconds that the browser will wait to redirect. Something to note, if the $time variable is set higher than 0, the script will not be killed at the redirect location so it will allow more content to be shown.
Tags: PHP
