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 and use require_once('') in my common includes section.

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


To use this function, call redirect('');. 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-2024 C. Shaun Wagner. All rights reserved.