Session variable is null when switching pages

Hello, this is my first post here.

I called session_start() on both pages right at the top, and yet when I load the other page that same session variable “user” (when I echo it) seems to be null and doesn’t execute the if else statement, I’ve been at this for two days now, really stuck.

session_id is set and the same on both pages, session_status() is 2 (active, but no one exists).

Here is my code:

I put it codepile, until I format this correctly, so sorry for the edits

https://www.codepile.net/pile/1Jp1G7qB

raw version:
https://www.codepile.net/raw/1Jp1G7qB.js

<?php
require 'DB/db.php';
require 'DB/session.php';

SessionManager::sessionStart("login_session");
//Comment when done with sessions
echo session_id();
echo "<br>";
echo session_name();
echo "<br>";
echo $_SESSION["user"] . " is now a session user.";
echo session_status();

if (!empty($_SESSION["user"])) {
    echo '<script type="text/javascript">$(document).ready(function () { ShowLogout(); });</script>';
} else {
    $error = "";
    foreach ($_POST as $key => $value) {
        if (empty($value)) {
            $error .= $key . " not inserted. \n";
        }
    }
    //var_dump($error);
    if (empty($error)) {

        $mail_to = "[email protected]";
        $mail_from = "From: SoftwareLL login";
        $mail_subject = "Date & Time of login: ";
        $mail_body = date("Y-m-d h:i:sa");

        mail($mail_to, $mail_subject, $mail_body, $mail_from);

        //echo "Connecting to DB... \n";

        $connection = new DB();
        $connection->connectDB();

        //Prijava
        $username = $_POST['usernameLogin'];
        $password = $_POST['passwordLogin'];
        $query = "SELECT * FROM korisnik WHERE "
                . "korisnicko_ime='{$username}' "
                . "AND lozinka='{$password}'";
        $result = $connection->selectDB($query);

        $authenticated = false;
        while ($row = mysqli_fetch_array($result)) {
            if ($row) {
                $authenticated = true;
                $type = $row['id_korisnik'];
            }

            if ($authenticated) {
                $_SESSION["user"] = $username;
                $_SESSION["type"] = $type;
                $ispis = $_SESSION["user"];
                echo '<script type="text/javascript">$(document).ready(function () { ShowLogout(); });</script>';
                echo "<br>" . $ispis . " logged in.";
            } else {
                echo "Login was unsuccessfull";
            }
        }

        $connection->closeDB();
    }
}



if (isset($_POST['registerBtn'])) {
    $error = "";
    foreach ($_POST as $key => $value) {
        if (empty($value)) {
            $error .= $key . " not inserted.";
        }
    }
    //var_dump($error);
    if (empty($error)) {

        //echo "Connecting to DB \n";
        $connection = new DB();
        $connection->connectDB();

        $name = $_POST['nameRegister'];
        $surname = $_POST['surnameRegister'];
        $username = $_POST['usernameRegister'];
        $password = $_POST['passwordRegister'];
        $email = $_POST['emailRegister'];
        $query = "INSERT INTO korisnik (ime, prezime, "
                . "korisnicko_ime, lozinka, email) VALUES ('{$name}','{$surname}','{$username}','{$password}','{$email}')";
        $result = $connection->selectDB($query);

        $connection->closeDB();
    }
}
?>
<!DOCTYPE html>

<html>
    <head>
        <title>Home</title>
        <meta charset = "UTF-8">
        <meta name = "viewport" content = "width=device-width, initial-scale=1.0">

        <meta name="title" content="SoftwareLL">
        <meta name="author" content="Ivan Slavko Matić">
        <meta name="keywords" 
              content="license, price, 
              company">
        <script src="javascript/jquery-3.4.1.min.js"></script>
        <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
        <script type="text/javascript" src="../javascript/main_jscript.js"></script>

        <link href="css/main.css" rel="stylesheet" type="text/css">
        <!-- Datatables include -->
        <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">


    </head>
    <body>
        <header style="font-weight:bold">
            <h1 id="headerID">Home</h1>
        </header>
        <nav>
            <ul>
                <li style="background-color: #007AA4; cursor: pointer;"><a href="">Home</a></li>
                <li style="cursor: pointer"><a href="">Gallery</a></li>
                <li style="cursor: pointer"><a href="webpages/administration.php">Administration</a></li>   
                <li style="cursor: pointer"><a href="">Documentation</a></li>
                <?php if (!empty($_SESSION["user"])) {
                    ?>
                    <li style="cursor: pointer" onclick="<?php SessionManager::deleteSession(); ?> reload();" id="logoutLi"><a>Logout</a></li>
                <?php } else { ?>
                    <li style="cursor: pointer" id="loginLi" class="loginLic" onclick="document.getElementById('modalLoginButton').style.display = 'block'" style="width:auto;"><a>Login</a></li> 
                    <li style="cursor: pointer" id="registrationLi" onclick="document.getElementById('modalRegisterButton').style.display = 'block'" style="width:auto;"><a>Registration</a></li>
                <?php } ?>
            </ul>
            <hr>
        </nav>

        <!-- Login form -->

        <!-- The Modal -->
        <div id="modalLoginButton" class="modal">
            <!-- Modal Content -->
            <form id="loginForm" class="modal-content animate" novalidate method="post" name="login" action="">

                <div class="container">
                    <h2 style="color: gray">Login</h2>
                    <label for="usernameLogin" style="color: gray;"><b>Username</b></label>
                    <input id="usernameLogin" type="text" placeholder="Username" name="usernameLogin" required>

                    <label for="passwordLogin" style="color: gray;"><b>Password</b></label>
                    <input id="passwordLogin" type="password" placeholder="Password" name="passwordLogin" required>
                    <br>
                    <label style="color: gray"> Remember me</label>
                    <input type="checkbox" checked="checked" name="rememberMeCheckbox">
                    <br><br>
                    <input name="loginBtn" type="submit" value="Log in" class="inputLoginButton" id="inputLoginButton">
                    &nbsp
                    <button type="button" onclick="document.getElementById('modalLoginButton').style.display = 'none'" class="cancelBtn" id="cancelBtn">Cancel</button>

                </div>
            </form>
        </div>

        <!-- Registration form -->

        <!-- Modal -->
        <div id="modalRegisterButton" class="modal">
            <!-- Modal Content -->
            <form class="modal-content animate" novalidate method="post" name="register" id="modalRegisterForm" action="">

                <div class="container">
                    <h2 style="color: gray">Registration</h2>
                    <label for="nameRegister" style="color: gray;"><b>Name</b></label>
                    <input type="text" placeholder="Name" name="nameRegister" id="nameRegister" required>

                    <label for="surnameRegister" style="color: gray;"><b>Surname</b></label>
                    <input type="text" placeholder="Surname" name="surenameRegister" id="surnameRegister" required>

                    <label for="emailRegister" style="color: gray;"><b>Email</b></label>
                    <input type="email" placeholder="Email" name="emailRegister" id="emailRegister" required>

                    <label for="usernameRegister" style="color: gray;"><b>Username</b></label>
                    <input type="text" placeholder="Username" name="usernameRegister" id="usernameRegister" required>

                    <label for="passwordRegister" style="color: gray;"><b>Password</b></label>
                    <input type="password" maxlength="15" placeholder="Password" name="passwordRegister" id="passwordRegister" required>

                    <label for="repeatPassword" style="color: gray;"><b>Repeat password</b></label>
                    <input type="password" maxlength="15" placeholder="Repeat password" name="repeatPassword" id="repeatPassRegister" required>
                    <br><br>
                    <input name="registerBtn" type="submit" value="Register" class="inputRegisterButton" id="inputRegisterButton">&nbsp
                    <button type="button" onclick="document.getElementById('modalRegisterButton').style.display = 'none'" class="cancelBtn" id="cancelBtn">Cancel</button>

                </div>
            </form>
        </div>

        <footer class="footer">
            <p><strong>Name & Surname: </strong>Ivan Slavko Matić</p>
            <p><strong>Last updated: </strong>Listopad, 2019. </p>
            <address><strong>Email: </strong><a href="mailto:[email protected]">[email protected]</a></address>
            <figure id="footer">
                <a href="http://validator.w3.org/#validate_by_uri+with_options">
                    <img src="multimedia/HTML5.png" 
                         alt="HTML5 validator" width="50" height="50"></a>
                <a href="http://jigsaw.w3.org/css-validator/">
                    <img src="multimedia/CSS3.png" 
                         alt="CSS validator" width="50" height="50"></a>
            </figure>
        </footer>
    </body>
</html>

Well, can’t read your code because it is not formatted. Part is in the middle. Please format it so it can be read and is not a huge run-on sentence. Thanks…

Now, to use sessions, the very first line should be “session_start();”…
In your code it appears, although hard to read, that you start off by requiring a class file and use the class to start the session. Not sure what that is all about. I am guessing that you were told to track session ID’s and insure they are active and not timed out in a cookie. (From your run-on text.) But, once a session is started, the browser keeps track of the session ID’s. You may not know this, but, cookies are sent inside the response headers on each request along with the session ID’s. You can read a cookie thru the $_COOKIE array if needed, but, no need to pass them yourself.
Perhaps you should repost your code so we can read it better and explain what is inside the session manager code…

You made it worse! Show us the code, using the QUOTES or PREPROCESSED tags in the reply window, not an image. Thanks!

I love OOP (even though PHP isn’t the greatest at doing it), but to simplify things greatly, just add the

session_start();

to the top of the pages that you want to utilize sessions.

Is it readable now ? Sorry for the hassle.

I did it exactly like you said, first line after <?php I did a session_start() and I did the same on the other page, and still nothing. Which is really weird, because the first page saves the value into session but when the page reloads or redirects to another page, the session variable gets wiped out.

I’ve added the missing formatting.

I have a feeling that using session_name is causing your issue.

That is NOT the first line…
session_start(); MUST be the FIRST line before you do anything else!
Also, it MUST be on every single page in your website as the first line.
And, you use session data inside of ONCLICK’s. That means your data is in Javascript calls which also means you can see it by viewing the source of the page. This is NOT secure at all.
The code “onclick=”<?php SessionManager::deleteSession();" Makes little sense. Well, depending what is inside your session manager’s object code. You can call PHP from a Javascript call. Normally, you would place a button there in the

  • and let the PHP code handle the process. Not sure what you are attempting to do with that code. Did you write this yourself or are you using a template from someone else?

    PS: Thanks for the editting of the code. We can read it very nicely now.

  • Just noticed, you left in email addresses. You should erase those. Or you will get a lot of SPAM.
    Never post live usernames, passwords or email address in any forum. Hackers scan these posts for them
    and you never know what they will do with them…

    Thank you for the tips and point outs. Yes, the session.php was from a Github user, it had nice features so I dropped my original session file. I’ll keep it simple, make some structure and clean up the code. It should work then.

    Well, you might be able to keep the session.php, but, just add session_start(); to the top of each page as the very first line right after <?PHP

    1 Like

    Technically, It should be the very first line before any output to the browser unless you are using a session variable before that. :grinning:

    Yes, but, since we do not know what all his requires and includes do, I suggest it goes first…

    That would be the best advice for sure. :grinning:

    @ErnieAlex @benanamen Guys I found out why my session variable user was null. @ErnieAlex was right, this php meddling among html’s onclick

    <?php if (!empty($_SESSION["user"])) {
                    ?>
                    <li style="cursor: pointer" onclick="<?php SessionManager::deleteSession(); ?> reload();" id="logoutLi"><a>Logout</a></li>
                <?php } else { ?>
                    <li style="cursor: pointer" id="loginLi" class="loginLic" onclick="document.getElementById('modalLoginButton').style.display = 'block'" style="width:auto;"><a>Login</a></li> 
                    <li style="cursor: pointer" id="registrationLi" onclick="document.getElementById('modalRegisterButton').style.display = 'block'" style="width:auto;"><a>Registration</a></li>
                <?php } ?>
    

    Was actually emptying/erasing/reseting my variable, once I removed all of my php inside html, it worked like a charm. Thank you a lot, I appreciate it immensely.

    Great! Always a thrill to solve a programming puzzle!

    We will see you in your next puzzle post!

    All the php code on any page is executed on the server when the page is requested. The original code was executing the deleteSession() method at that time. While you can make a http get request to the server as part of the onclick javascript code, that will cause php code on the newly requested page to be executed, you should use a post method form when causing any action to take place on the server, such as logging a user out.

    Sponsor our Newsletter | Privacy Policy | Terms of Service