-1

I have been attempting to create a user login script in PHP, however I am met with an error telling that $_SESSION["username"] is undefined. I have session_start() inside of $_SERVER["DOCUMENT_ROOT"] . "/assets/php/main.header.php", however the variable still shows as undefined.

<?php
    if (!isset($_SESSION["username"])) {
        header("Location: /en/");
    }
?>
<!DOCTYPE html>
<html>
    <head>
        <?php
            include($_SERVER["DOCUMENT_ROOT"] . "/assets/php/main.header.php");
        ?>
        <title>Profile | Project Club</title>
    </head>
    <body>
        <h1>Profile</h1>
        <p><?php echo $_SESSION["username"]?></p>
        <?php
            include($_SERVER["DOCUMENT_ROOT"] . "/assets/php/main.footer.php");
        ?>
    </body>
</html>
4424dev
  • 118
  • 1
  • 13

1 Answers1

2

Use session_start() at the beginning of the code.

Buddy
  • 10,627
  • 5
  • 40
  • 57
Sagnik Paul
  • 63
  • 1
  • 6
  • I have session_start() in header.php – 4424dev May 21 '18 at 23:28
  • 1
    You are trying to access the session variable before starting the session. I hope you understood where the error is? After starting the session, you should try to access the session variable. – Sagnik Paul May 21 '18 at 23:29
  • I have an isset at the beginning to detect if it is set, and if it isn't set, it should redirect to /EN/ – 4424dev May 23 '18 at 19:46
  • 1
    Suppose you have a box of sweets. The box is sealed. You're trying to count the number of sweets in it. Is it possible? First you need to open the box of sweets and then check. Similarly at first write session_start() and then check if the session variable is present. – Sagnik Paul May 23 '18 at 19:49