1

The following header function is not working. I ma trying to go to login if the user is not logged in -

    <?PHP
    if (logged_in() === false) {
    header('Location: login.php');
    }
    ?>

However if I do -

    <?PHP
    if (logged_in() === false) {
    echo"No user is logged in";
    }
    ?>

It does echo it and I can see that it says no user is logged in

It is basically just checking if there is a user logged in

    function logged_in() {
    return (isset($_SESSION['user_id'])) ? true : false;
    }
avink
  • 55
  • 1
  • 5

3 Answers3

2

Try to put exit() or die() after the header like

  if (logged_in() === false) {
      header('Location: login.php');
      exit();    //or die();
  }

But makesure that your login.php should be in the same folder

GautamD31
  • 28,552
  • 10
  • 64
  • 85
1

Make sure that there is no output(white-space also) in your code.

you can use ob_start() and ob_end_flush() to clear out-put.

<?php ob_start();

 // code 

ob_end_flush(); ?>
Fasil kk
  • 2,147
  • 17
  • 26
0

You probably need to include the fully qualified domain and path to the new url. There is a note on the official documentation for the header function indicating as such.

Note:

HTTP/1.1 requires an absolute URI as argument to » Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. You can usually use $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative one yourself:

This note also contains the following code sample.

<?php 
/* Redirect to a different page in the current directory that was requested */ 
$host  = $_SERVER['HTTP_HOST']; 
$uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); 
$extra = 'login.php';
header("Location: http://$host$uri/$extra"); 
exit; 
?>
Thomas
  • 1,402
  • 1
  • 11
  • 14
  • Every browser supports relative URLs, and W3C or IETF is planning on changing the spec to say that it's allowed. – Barmar Jun 07 '13 at 05:25
  • See http://stackoverflow.com/questions/8250259/is-a-302-redirect-to-relative-url-valid-or-invalid – Barmar Jun 07 '13 at 05:26