-1

I'm trying to create a session where the user is required to be logged in before accessing a page. Essentially I want them to be alerted that they need to be logged in before re-directing them to the login page.

<html>
    <body>

        <?php
        if (isset($_SESSION['username'])) {
            $username = $_SESSION['username'];
            echo "<p>Username: $username</p>\n";
        } else {    
            header('Location: login_home.html');
            echo "<script type='text/javascript'>alert('Please login to view this page')</script>";
        }
        ?>
    </body>
</html>

At the moment it is just re-directing without alerting any information.

Rotimi
  • 4,783
  • 4
  • 18
  • 27
harry
  • 19
  • 6
  • outputting before header – Funk Forty Niner Mar 26 '18 at 13:37
  • This does — not — work. You must — not — have output before the `header`. – deEr. Mar 26 '18 at 13:38
  • As mentioned in the [documentation](http://php.net/manual/en/function.header.php). Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. – Tyler Mar 26 '18 at 13:39

1 Answers1

2

You can't redirect with php header() and have output before. This is because, as the name said, it will redirect the user only be the HTTP Header. So this will happens before the rendering of the browsers content and will throw an error by php, if you had output before calling header().

But you could simply redirect using javascript:

<script type='text/javascript'>
    alert('Please login to view this page');
    window.location.replace('login_home.html');
</script>
eisbehr
  • 12,243
  • 7
  • 38
  • 63
  • Would each line need to be echo'd if it is in PHP markers? – harry Mar 26 '18 at 13:42
  • For a more detailed post regarding `window.location.href` see [this post](https://stackoverflow.com/a/506004/6009304). It's basically explains `replace` vs `href` and what is the better solution for a basic scenario. – Tyler Mar 26 '18 at 13:42
  • @Thomas you can combine the echo statements into 1. Either concatenate each line together or just wrap the entire block with double quotes. I personally prefer concatenating the lines. Ultimately it will have to be echoed or be placed in a JavaScript file/script block. – Tyler Mar 26 '18 at 13:44
  • You could write this in one line, as you did in the question, too. I just used multiple lines for better readability. @Thomas – eisbehr Mar 26 '18 at 13:45
  • I've put echo ""; but it still seems to just re-direct with no alert? – harry Mar 26 '18 at 13:47
  • And @Tyler has a good point here, `replace` is the better choice, regarding your initial question. But both, `replace` and `href` will work. – eisbehr Mar 26 '18 at 13:47