Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

redirect - PHP if-statement ignored when header(Location: xxx) is inside

I have a strange problem. There is an if-statement at the top of my page that seems to be ignored when a header(location: xxx) commmand is inside of it.

$check = $authorisation->check(); 
// i know this results in true by echoing the value 
// (you've got to believe me on this one)

if(!$check){
    // redirect to message
    header("Location: message.php");
    exit;

}else{
    // do nothing, continue with page
}

This ALWAYS redirects to the message.php page, no matter what the outcome of $authorisation->check() is!

Strange thing is, when I comment out the header-command, and put echo's in the if-statement for verification, all works as to be expected:

    $check = $authorisation->check(); // true
    if(!$check){
        // redirect to message
        echo "you are not welcome here";
    }else{
        echo "you may enter";
    }

The result is "you may enter";

This also works as expected:

    $check = true;
    if(!$check){
        // redirect to message
        header("Location: message.php");
        exit;

    }else{
        // do nothing
    }

This only redirects to the message page when $check = false;

Last funny thing is that I experience the problem only on 1 server, same script works flawlessly on testserver.

Any help would be much appreciated!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Call the exit function after redirecting to another page, otherwise the following code will be executed anyway.

if(!$check){
  // redirect to message
  header("Location: message.php");
  exit;
}else{
  // do nothing, continue with page
}
// the following code will be executed if exit is not called
...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...