0

if want a single PHP file to reirect to different pages according to different conditions say depending on the outcome of a post..

if(condition 1) {
    header("Location: page1.php");
    exit;
}
else if(condition 2) {
    header("Location: page2.php");
    exit;
}
else {
    header("Location: page3.php");
    exit;
}
5
  • Which problems are you facing? Commented Jul 9, 2013 at 18:16
  • That should work as long as no whitespace has been output. Commented Jul 9, 2013 at 18:17
  • no problems but unsure if this right Commented Jul 9, 2013 at 18:17
  • Yes - you can do that. Commented Jul 9, 2013 at 18:17
  • with that, you'd only ever issue one header, because the script aborts at each condition anyways. no, there's nothing wrong with it. gets ugly very quickly, but nothing "wrong". Commented Jul 9, 2013 at 18:17

4 Answers 4

1

Aboslutely!

You might want to make sure the headers haven't been sent first. You can use headers_sent for this

if (!headers_sent()) {
  // ...
}

A good way to handle this might be

function redirect_to($location) {
  if (headers_sent($filename, $line)) {
    trigger_error("Headers already sent in {$filename} on line {$line}", E_USER_ERROR);
  }
  header("Location: {$location}");
  exit;
}

// you can now use it like this
if(condition 1) {
  redirect_to("page1.php");
}
else if(condition 2) {
  redirect_to("page2.php");
}
else {
  redirect_to("page3.php");
}
Sign up to request clarification or add additional context in comments.

Comments

0

Assuming that your condition N if statements are valid, there's nothing wrong with having different headers for different cases.

Comments

0

Yes, as long as nothing was outputted before any header() call.

Comments

0

Yes that should work provided you don't echo anything onto the page before calling that function. You can have as much PHP as you like as long as you don't print anything out upstream of the header function.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.