Search code examples
phphtmlheaderechooutput-buffering

PHP Echos and headers - Echos not being outputted


I have a section by which if a Session variable username is not in place, the application should output an error message stating that Credentials are required and then redirect the user to a login page. The issue is that, only the latter is happening, and the "error message" is not being outputted.

<?php if (!isset($_SESSION['username'])){  
    ob_start();
    echo "<script type='text/javascript'>alert('Not logged in. Please input required credentials.');</script>";
    header('location: /se7en/login.php');
    ob_end_flush();

}
?>

I tried using an Output Buffer to counteract this issue, however, the same issue kept happening. How can I resolve this, please?

Many thanks!


Solution

  • I usually handle this need by having the page I'm redirecting to post the message. One way would be this:

    <?php if (!isset($_SESSION['username'])){  
        ob_start();
        header('location: /se7en/login.php?message=Not logged in. Please input required credentials.');
        ob_end_flush();
    
    }
    ?>
    

    Then on your login.php you'd have

    if ( ! empty( $_GET['message'] ) ) {
        $message = htmlspecialchars( $_GET['message'] );
        echo "<script type='text/javascript'>alert('$message');</script>";
    }
    

    You could also just pass a message number (message=1) and then have all the possible messages in an array in your login.php file:

    $messages = array(
        1 => "Not logged.....",
        2 => "something else...",
        //...
    );
    if( ! empty( $_GET['message'] ) && ! empty( $messages[ $_GET['message'] ] ) {
        echo "<script type='text/javascript'>alert('{$messages[ $_GET['message'] ]}');</script>";
    }