0

I've got a problem with the header function

if ( ! isset($_SESSION['user']) ) {

   header('Location: login.php');

}

There is no echo before the if, the page is empty!

it doesn't redirect me. I've var_dump();'ed something in the If statement and it worked so the if is correct.

The php version is 5.6

7
  • Do you have any error ? Is there anything echoed before ? Commented Oct 20, 2015 at 9:15
  • Nothing echoed before Commented Oct 20, 2015 at 9:16
  • 1. Do you enter the if-statement? 2. Do you have any kind of output before this? Headers has to be called before any output is made to the browser (whitespace, HTML-coding, echo from PHP). Commented Oct 20, 2015 at 9:16
  • any output or HTML before the header function could make it fail. Also a so called Byte Order Mark (BOM) could let it fail.en.wikipedia.org/wiki/Byte_order_mark Commented Oct 20, 2015 at 9:19
  • turn on error reporting and set display_errors on 1 then if there are errors probably because you have sent some output to browser like white char then fix it Commented Oct 20, 2015 at 9:24

4 Answers 4

5

You might have outputted something to the browser before header call. First check:

  • is there any html before php opening tag

  • is there any whitespace before php opening tag

  • is another php script included with echo before that script

  • is the coding utf8 with BOM?

Those are possible reasons of your error.

Sign up to request clarification or add additional context in comments.

Comments

2

Try this code :-

<?php
if ( ! isset($_SESSION['user']) ) {
?>
<script>
    window.location = 'login.php';
</script>
<?php
}
?>

1 Comment

@Floes Take a look at the answer @n-dru posted instead. Most likely your header isn't working because of charset encoding, or having some kind of output before the header is called. This solution isn't optimal, as it won't work if JavaScript is disabled in the browser. Also, always remember to use exit; after calling a redirect, to stop the rest of the script from executing.
1

You can also do following:

echo "<script>window.location = 'login.php';</script>";

Comments

-1

white space may cause the redirect change it to something like

if ( ! isset($_SESSION['user']) ) {

   header('location:login.php');

 }

3 Comments

That really doesn't matter, the issue is most likely either a session not started or output before the header is called. (Not my downvote btw).
the session not started is true, there is no output before the header
@Floes Post your all page code so that it get's clear to everyone

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.