开发者

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开发者_Go百科 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!


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
...


you should always run exit after you are finished with headers so that the transfer is faster and more stable for the browser.

Try this way:

if( ... )
{
     header("Location: message.php");
     exit;
}

// ...

Please read the comment for other tip's on why this is a good idea.


Try to put error_reporting(-1); you will see something new. On one of your servers, the PHP error reporting is set to lower level.


This sort of error is often caused by content being sent to the browser before the header function is called.

Even if you don't think you are sending content, if your file starts with a space or blankline before "< ? php" then you will hit an error - this is often quite a subtle thing to notice/find.

Output buffering can allow you to call the header function even after you've "sent" content out - this is probably why the page works on one server and not another.


suggestion:

  • write ob_start() at the top and

  • also write exit(); after header();

  • debug with error_reporting(-1) as suggested in one answer


I had the same problem, you are calling header('Location: blahblah') somewhere else in the code. check it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜