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

I have a strange problem. At the top of my page is an if statement, which seems to be ignored when the header (location: xxx) command is inside 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 is ALWAYS redirected to the message.php page, regardless of the result of $ authorization-> check ()!

Strange, when I comment out the header command and add echo to the if-statement for verification, everything works as expected:

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

Result: "you can 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;

The funny thing is that I only have a problem on one server, the same script works flawlessly on testerver.

Any help would be greatly appreciated!

+2
redirect php header if-statement
source share
6 answers

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

Try as follows:

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

Please read the comment for other tips on why this is a good idea.

+4
source share

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

 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 ... 
+4
source share

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

+2
source share

This error often occurs because content is 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 a space before "<? Php", then you will get an error - this is often a pretty subtle thing to notice / find.

Output buffering may allow you to call the header function even after you β€œsent” the content - this is probably why the page is running on one server and not on another.

+2
source share

sentence:

  • write ob_start() at the top and

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

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

0
source share

I had the same problem: you call the header ("Location: blahblah") somewhere else in the code. check it out.

0
source share

All Articles