PHP Page Redirection

To redirect to a different page using PHP you can use the header() function with the parameter 'Location: ' and the destination of the redirect.

header('Location: http://www.hashbangcode.com');

However, if any headers are sent before this function call then the script will fail. To get around this you can either ensure that nothing is printed out on the page, or if that is not possible for some reason then you can use a JavaScript redirect. The headers_sent() function will allow you to see if any headers have been sent to the browser yet, if they have then you will need to use the JavaScript redirect like this:

location.href='http://www.hashbangcode.com';

You will want to redirect a user even if they have JavaScript turned off so you can also put in a noscript tag with a meta refresh tag. A meta refresh is a HTML tag that tells browsers to refresh the page, with the content tag being the amount of time to wait before the refresh. Adding the URL parameter into the content tells the browser to refresh to a different URL, essentially a redirect.

<meta http-equiv="refresh" content="0;URL=http://www.hashbangcode.com" />

Here is the full version.

$url = 'https://www.hashbangcode.com';
if (headers_sent()) {
 // redirect using JavaScript if it has, meta redirects if not
 echo '<script type="text/javascript">location.href=\'' . $url . '\'</script><noscript><meta http-equiv="refresh" content="0;URL=' . $url . '" /></noscript>';
} else {
 // otherwise use the php way.
 header('Location:' . $url);
 exit();
};

It is still possible for a user to stop any meta redirects, this should redirect 99% of users to another page if headers have already been sent, but your best bet is to use the header() function whenever possible.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
4 + 0 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.