简体   繁体   中英

PHP $_SESSION Lost When Refreshing

I have an issue with my $_SESSION variables in my website. For some reason, they seem to reset themselves whenever I reload a page, or if I browse to another section of the website.

I have a few different files.

The session of the site is started in the "config.php" file.

config.php

<?php
  // Start Session
  session_start();
  // Turn on all error reporting
  ERROR_REPORTING(E_ALL);
  ini_set('display_errors', 1);

  require_once('classes/database.php');
  $link = new DATABASE;

  // Include User info
  require_once('classes/user.php');

  // Create instance for user class
  $activeUser = new USER($link);
?>

index.php has the initial login screen. It also checks to see if someone is already logged in by calling a function in my USERS class.

index.php

<?php
require('config.php');
// Check if user is already logged in
if($activeUser->isLoggedIn()) {
    $activeUser->redirect('home.php');
}

// Logging user into system
if(isset($_POST['login'])) {
    $username = $_POST['user'];
    $password = $_POST['pass'];

    if($activeUser->login($username, $password)) {
        $activeUser->redirect('home.php');
    }

    else {
        $activeUser->error = "true";
        $activeUser->errorMessage = "Username or password is incorrect";
    }
}

print_r($_SESSION);
?>
<!doctype html>
<html>
  <head>
      <meta charset="UTF-8">
      <title>IMD 2000 - Term Project (Will And Tyson)</title>
  </head>

<body>
    <form id = "registrationForm" method = "POST">
        <section id = "loginBox">
            <div id = "loginItems" name = "userBox">
                Username: <input type = "text" name = "user" required placeholder = "Username" /> <!-- Username input -->
            </div>

            <div id = "loginItems" name = "passwordBox">
                Password: <input type = "password" name = "pass" required placeholder = "Password" /> <!-- Password input -->
            </div>

            <div id = "loginItems" name = "loginBox">
                <input type = "submit" value = "Log In" name = "login" /> <!-- Log in to site -->
            </div>
        </section>
    </form>

    <section id = "loginBox" name = "create">
        <a href = "newAccount.php">
            <input type = "button" value = "Create New Account" name = "createNew" />
        </a>
    </section>

    <section id = "errorBox">
        <?php
            if($activeUser->error == "true") {
                echo $activeUser->errorMessage;
            }
        ?>
    </section>

  </body>
</html>

I put in print_r($_SESSION) so I could verify that the session was being re-started on login.

Anyway, once you've logged in to the system, it directs you to the home page, "home.php"

home.php

<?php
require_once('config.php');

echo $_SESSION['username'];
  if(!$activeUser->isLoggedIn()) {
    header("Location: index.php");
  }
  print_r($_SESSION);
  ?>
<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Home</title>
    <link rel = "stylesheet" href = "styles/homestylesheet.css">
</head>

<body>
    <header class="site-header">
        <nav>
            <ul>
                <li><a href = "home.php">Home</a></li>
                <li><a href = "userInfo.php">Your Profile</a></li>
                <li><a href="">Name</a></li>
                <li><a href = "<?php $activeUser->logout();?>">Log Out</a></li>
            </ul>
        </nav>
    </header>



    <h1>Home</h1>

    <form id = "registrationForm" method = "POST">
        <section id = "loginBox">
            <div id = loginItems name = "userBox">
                <input type = "text" name = "user post" placeholder = "post" required />
                <input type = "submit" name = "submit" value = "post" />
            </div>

            <div>
                <a><img src="Friendface.png" alt="Friendface"/>PosterName</a>
                <div>
                    <post>
                        tex here
                    </post>
                </div>
            </div>

            <div>
                <a><img src="Friendface.png" alt="Friendface"/>PosterName</a>
                <div>
                    <post>
                        tex here
                    </post>
                </div>
            </div>
        </section>
    </form>

    <section id = "errorBox">
        <?php if ($activeUser->error = "true") {echo $activeUser->errorMessage;}?>
    </section>
  </body>
</html>

Both of these files call on functions defined in my user.php class file.

classes/user.php

<?php
class USER
{
    // Set error to false, and blank error message
    public $error = "false";
    public $errorMessage = "";

    private $conn;

    // All the variables needed for the user profile.
    public $username;
    public $userID;
    public $password;
    public $firstName;
    public $lastName;
    public $emailAddress;
    public $address;
    public $city;
    public $province;
    public $country;

    // OOP variable setting
    function __construct($conn){
        $this->conn = $conn;
    }

    // Create a new user
    function createNewUser($username, $password) {
        // Clean inputs
        $username = trim($username);
        $password =  trim($password);

        // Encrypt password
        $password = password_hash($password, PASSWORD_DEFAULT);

        // Check if username already exists
        $checkSQL = "SELECT * FROM users WHERE username = '$username'";
        $checkResult = $this->conn->queryDB($checkSQL);
        if(mysqli_num_rows($checkResult) > 0) {
            $this->error = "true";
            $this->errorMessage = "This username has already been taken. Please try again";
            return false;
        }

        // Username does not exist, insert into database
        else {
            $insertSQL = "INSERT INTO users(username, password) VALUES('$username', '$password')";
            $insertResult = $this->conn->queryDB($insertSQL);

            // Get the USER ID that is inserted into the function, to be used in the next phase of registration
            $userID = mysqli_insert_id($this->conn->getConnected());
            // Set the SESSION globals
            $_SESSION['username'] = $username;
            $_SESSION['userID'] = $userID;
            return true;
        }
    }

    // Add or Edit User Info
    function userInfo($firstName, $lastName, $address, $city, $province, $country) {
        // Clean Inputs
        $firstName = trim($firstName);
        $lastName = trim($lastName);
        $emailAddress = "fakeyfakefake@fakeemail.com";
        $address = trim($address);
        $city = trim($city);
        $province = trim($province);
        $country = trim($country);
        $userID = $_SESSION['userID'];

        // Validate first and last name, as they are the only required identifiers.
        if(empty($firstName) || empty($lastName)){
            $this->error = "true";
            $this->errorMessage = "Please enter a value for First AND Last Name";
        }

        // Important values are valid, insert into database. 
        else {
            // Check if user information is already set for User. If it is, we will use the UPDATE SQL query. If not, we will use the INSERT query
            $userInfoCheckSQL = "SELECT userID FROM userInfo WHERE userID = '$userID'";
            $userInfoCheckResult = $this->conn->queryDB($userInfoCheckSQL);
            $count = mysqli_num_rows($userInfoCheckResult);
            if ($count == 1) {
                $updateUserInfoSQL =    "UPDATE userInfo
                                         SET    firstName = '$firstName'
                                                lastName = '$lastName'
                                                address = '$address'
                                                city = '$city'
                                                province = '$province'
                                                country = '$country'
                                        WHERE userID = '$userID'
                                        ";
                $updateUserInfoResult = $this->conn->queryDB($updateUserInfoSQL);

                return true;
            }

            // User Info Does not exist for this user
            else {
            $addUserInfoSQL = "INSERT INTO userInfo(userID, firstName, lastName, emailAddress, address, city, province, country) VALUES('$userID','$firstName','$lastName','$emailAddress','$address','$city','$province','$country')";
            $addUserInfoResult = $this->conn->queryDB($addUserInfoSQL); 
            return true;
            }
        }
    }

    // Gather User Info From Database
    function fetchUserInfo() {
        $userID = $_SESSION['userID'];
        $fetchInfoQuery = "SELECT users.username, userInfo.* FROM users JOIN userInfo ON users.userID = userInfo.userID WHERE userInfo.userID = '$userID'";
        $fetchInfoResult = $this->conn->queryDB($fetchInfoQuery);
        $row = mysqli_fetch_array($fetchInfoResult, MYSQLI_ASSOC);
        $count = mysqli_num_rows($fetchInfoResult);

        if($count == 1) {

            $username = $row['username'];
            $firstName = $row['firstName'];
            $lastName = $row['lastName'];
            $emailAddress = $row['emailAddress'];
            $address = $row['address'];
            $city = $row['city'];
            $province = $row['province'];
            $country = $row['country'];

            /*
            // Create a Table to display the information
            echo "<table id = 'userInfoTable'>";

            // Create Rows and columns to store all the info
            echo "<tr><td>Username:</td><td>$username</td></tr>";
            echo "<tr><td>First Name:</td><td>$firstName</td></tr>";
            echo "<tr><td>Last Name:</td><td>$lastName</td></tr>";
            echo "<tr><td>E-Mail Address:</td><td>$emailAddress</td></tr>";
            echo "<tr><td>Address:</td><td>$address</td></tr>";
            echo "<tr><td>City:</td><td>$city</td></tr>";
            echo "<tr><td>Province:</td><td>$province</td></tr>";
            echo "<tr><td>Country:</td><td>$country</td></tr>";

            // Close the table
            echo "</table>";
            */
            return true;
        }
        else {
            return false;
        }
    }

    // Log in function
    function login($username, $password) {
        $sql = "SELECT * FROM users WHERE username = '$username'";
        $result = $this->conn->queryDB($sql);
        $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
        // Validate the hash of the password
        $valid = password_verify($password, $row['password']);
        if ($valid) {
            // Set Session Variables
            $_SESSION['username'] = $username;
            $_SESSION['userID'] = $row['userID'];

            return true;
        }
    }

    // Check if user is already logged in function
    function isLoggedIn() {
        if(isset($_SESSION['username'])) {
            return true;
        }
    }

    // Redirect to different section of site function
    function redirect($url) {
        session_write_close();
        header("Location: $url");
        exit;
    }

    // Log out function
    function logout() {
        $_SESSION = array();

        // Delete the cookies! 
        if(ini_get("session.use_cookies")) {
            $params = session_get_cookie_params();
            setcookie(session_name(), '', time()-42000,
                      $params["path"], $params["domain"],
                      $params["secure"], $params["httponly"]
                      );
        }

        // Destroy the session
        session_destroy();
    }

    /*
    // Delete User Account
    function deleteAccount() {
        global $conn;
        checkLoginStatus();

        // Delete user info first
        $sqlDeleteInfo = "DELETE FROM userInfo WHERE userID = '$userID'";
        $deleteInfoResult = $conn->query($sqlDeleteInfo);
        if($deleteInfoResult) {
            echo "User info deleted successfully<br>";
            $sqlDeleteAccount = "DELETE FROM users WHERE userID = '$userID'";
            $deleteAccountResult = $conn->query($sqlDeleteAccount);

            if ($deleteAccountResult){
                echo "Account has been deleted successfully.<br>";
                echo "Please click <a href = 'index.php'>here</a> to return to the index page.";
                session_destroy();
            }

            else {
                "Error while deleting account <br>";
            }
        }

        else {
            echo "Error while deleting user info<br>";
        }
    }*/
  // End of class
  }
?>

I believe the issue stems from somewhere in the redirect function or the logout function itself, but I can't for the life of me figure out why. The session is only started in the config file, which is included everywhere it needs to be, and the only time I tell the site to destroy the session is in the logout function, which I only call when I click the "Log Out" link on the home page.

I'd really appreciate any help on this that people can provide. I've spent far longer than I'd like to admit trying to figure this out.

Many thanks!

UPDATE: I created a new php file and tested the session update. The session updates perfectly on my test file.

sessionTest.php

<?php
  include('config.php');

  echo "This is testing " . $_SESSION['test'] . "sessions";
  $_SESSION['test'] = "updating ";

  //session_destroy();
?>

After some more in-depth research, I've found my issue!

<li><a href = "<?php $activeUser->logout();?>">Log Out</a></li>

This code executes the function whether the link is clicked or not.

I have since repaired this with a few tweaks.

Firstly, switch the above code to:

<li><a href = "home.php?logout=callLogoutFunction">Log Out</a></li>

Secondly, in the __construct of my user class:

if(isset($_GET['logout']) && $_GET['logout'] == "callLogoutFunction")
{
  $this->logout();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM