PHP Redirect

This function is used to redirect a user from the current page to a new URL. You can embed a query string into the URL.

The Code

I put the code right up front for those who want it. Copy this into your PHP code. I personally save it in a file called redirect.inc and use require_once('redirect.inc') in my common includes section.

	function redirect($url) {
		header('Location: '.$url);
		die("<html>
			<meta http-equiv='refresh' content='0; $url'>
			<body onload=\"location.replace('$url');\">
			<a href='$url'>$url</a>
			</body></html>");
	}

Usage

To use this function, call redirect('http://shaunwagner.com');. You will replace the URL with the URL you want to redirect to. This is just like the URL in a form or a tag. If you don't use http://, it will be a relative URL. You can embed variables in the query string, such as redirect('login.html?error=Invalid+Username');

If you aren't using an output buffer, you must not send any data to the user before using the redirect function. You will get an error that you sent a header value after sending data. One solution is to use an output buffer (see ob_start in the PHP documentation). The other solution is to make sure all redirects come first.

You've read it. You can't unread it.
Copyright ©1998-2017 C. Shaun Wagner. All rights reserved.