I design & develop websites.

I am a designer & developer. I am a communicator & strategist. I can add value to your business.

PHP Redirect / Refresh Function

Often I find myself redirecting users between pages using varying methods depending where in the program flow the redirect is required (i.e. have the headers been sent). I decided to write a function which took the effort out of redirecting or refreshing (with a delay) a page.

<?php
function redirect($location, $delay = 0) {
	if (!headers_sent()) {
		if ($delay > 0) {
			header("Refresh: $delay; url=$location");
		} else { header("Location: $location"); }
	} else {
		?>
		<script type="text/javascript" charset="utf-8">
			$(function () { 
				setTimeout(function() { 
					window.location.replace('<?php echo $location; ?>');
				}, <?php echo $delay*1000; ?>); 
			});
		</script>
		<noscript>
			<meta http-equiv="refresh" content="<?php echo $delay; ?>;url=<?php echo $location; ?>">
		</noscript>
		<?php
	}
}
?>

The script first tries to redirect the page using the header() function. If the headers have not been sent and then falls back to jQuery, resorting finally to a meta refresh if javascript is disabled.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>