Search code examples
phpfilevariablessessionsession-variables

How do I use a $_SESSION['variable'] from one session in another?


I'm making a web app where the user logs in and is able to access the profile and take a quiz. I've got most of it working the only problem is, is that it seems to 'forget' which user is signed in. By this I mean I can't access any of the variables from when the user logs in session. For example, I have a $_SESSION['username'] = $username; which returns unidentified variable when I try to use the variable $username in a different session or page. Also, I haven't terminated my login session.

Right now I'm trying to store the results of my quiz to a database along with the user's username but it only stores the score and not the username.

Below is my code.

authenticate.php file (This contains the variables regarding usernames)

<?php
session_start();
// Change this to your connection info.
$DB_HOST = 'localhost';
$DB_USER = 'root';
$DB_PASS = '';
$DB_NAME = 'phplogin';
// Try and connect using the info above.
$con = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ( mysqli_connect_errno() ) {
    // If there is an error with the connection, stop the script and display the error.
    die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// Now we check if the data was submitted, isset will check if the data exists.
if ( !isset($_POST['username'], $_POST['password']) ) {
    // Could not get the data that should have been sent.
    die ('Username and/or password does not exist!');
}
// Prepare our SQL
if ($stmt = $con->prepare('SELECT username, password FROM users WHERE username = ?')) {
    // Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
    $stmt->bind_param('s', $_POST['username']);
    $stmt->execute();
    $stmt->store_result();
    // Store the result so we can check if the st_account exists in the database.
    if ($stmt->num_rows > 0) {
        $stmt->bind_result($username, $password);
        $stmt->fetch();
        // st_account exists, now we verify the password.
        if (password_verify($_POST['password'], $password)) {
            // Verification success! User has loggedin!
            $_SESSION['loggedin'] = TRUE;
            $_SESSION['name'] = $_POST['username'];
            $_SESSION['username'] = $username;
            include_once 'homepage.php';

            // echo 'Welcome ' . $_SESSION['name'] . '!';
        } else {
            echo 'Incorrect username and/or password!';
        }
    } else {
        echo 'Incorrect username and/or password!';
    }
    $stmt->close();
} else {
    echo 'Could not prepare statement!';
}
?>

final.php file

<php include "process.php"?>

lines 24 - 44

    <main>
        <div class="container">
             <h2>You are Done!</h2>
             <p>Congrats! You have completed the test</p>
             <p>Final score: <?php echo $_SESSION['score']; ?></p>
           <?php echo $score; ?>
             <a href="question.php?n=1" class="start">Take Test Again</a>
           <?php
           $DB_HOST = 'localhost';
           $DB_USER = 'root';
           $DB_PASS = '';
           $DB_NAME = 'phplogin';
           $con = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
            $query = "INSERT INTO `results`(`username`,`score`) VALUES ($username, $score)";
            mysqli_query($con, $query);
            ?>



             <?php session_destroy(); ?>
        </div>

I don't know if it's necessary to include process.php but I thought it might be helpful to show where the $score variable comes from.

process.php file (this isn't the whole file.)

<?php include 'database.php'; ?>
<?php session_start(); ?>
<?php
    //Check to see if score is set_error_handler
    if (!isset($_SESSION['score'])){
        $_SESSION['score'] = 0;
    }
    $score = $_SESSION['score'];

}
?>

Sorry if I've made a really simple stupid error, don't hate me, I'm still pretty bad at coding.


Solution

  • Put your session_start(); at the very top of your code, for example, at the very top of your final.php file rather than in your process.php file.

    E.g.;

    <?php
        session_start();
        include 'database.php'; 
    ?>