Joshua Joshua - 3 years ago 100
HTML Question

Trying to execute HTML after PHP code

I am making a website where you can log in using HTTP Basic Authentication. Once a person logs in with the correct credentials, it will start a new session and have a link to continue to the another page. On the other page I want it to check to see if a session has been started by getting the username session variable that I created on the last page. If the session variable exists, I want it to execute the pages HTML code. If the session variable does not exist, It should give the user a link to the login page. Does anyone know how this can be achieved?

// Second page checking to see if the session variables exists code
<?php
session_start();
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
// Command to execute rest of webpage after PHP closing tag
} else {
die("<a href='index.php'>Login</a>");
}
?>

<!-- HTML CODE THAT NEEDS TO BE EXECUTED -->
<p>Hi!</p>

Answer Source

You could try and wrap your webpage content around an if in PHP tags.

<?php
    session_start();

    if (isset($_SESSION['username'])) {
        $username = $_SESSION['username'];
        ?>
            <p>Hi!</p>
        <?php
    } else {
        die("<a href='index.php'>Login</a>");
    }
?>

EDIT

After some consideration, die would be unneeded. You can just do the same for the if. This would return the result, and would also execute additional PHP code in the file if needed.

<?php
    session_start();

    if (isset($_SESSION['username'])) {
        $username = $_SESSION['username'];
        ?>
            <p>Hi!</p>
        <?php
    } else {
        ?>
            <a href='index.php'>Login</a>
        <?php
    }
?>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download