Redirecting The Page In PHP

To redirect the current page to a different location you use the header() function in the following way:

header("http://www.hashbangcode.com");

You can use this function when you want to point the user to a different page. If you are writing a login script then this function would be useful to show the user a certain page depending on them entering the correct user information.

To send a code along with the redirect (for example, a 301) you can use the optional parameters. The second parameter is a boolean value that determines if this header call should replace any headers of a similar name. For example, if you send a header called "Cache-Control" and then send another header later on with the same name then the second parameter determines if the value is replaced or appended. If the value is true then the previous value is overwritten, if the value is false then the value is appended to the list of headers being sent.

The third parameter is the code to be issued along with the header. So to create a 301 redirect do the following.

header("http://www.hashbangcode.com",false,301);

The is a problem with the headers() function is that it will cause errors if any output has already been sent to the browser, including other headers. To get around this you can use the headers_sent() function, which checks to see if any headers have been sent. If they have then it returns true, if not then false is returned. So with this in mind we can create a neat little check to redirect the page in both cases. If headers have already been sent then the JavaScript property location.href can be used to redirect the page in the same way.

// set up redirect URL
$url = "http://www.hashbangcode.com";
if ( headers_sent() ) {
  // redirect using JavaScript if it has
  echo "";
  exit();
} else {
  // otherwise use the php way.
  header("Location:".$url);
  exit();
}

This works as long as the user has JavaScript turned on, if they don't then you might have to just provide them with a link to allow them to progress.

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
5 + 15 =
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.