2016-12-05 4 views
0

Ich habe ein Problem mit meinen $ _SESSION-Variablen in meiner Website. Aus irgendeinem Grund scheinen sie sich zu resetten, wenn ich eine Seite neu lade oder wenn ich zu einem anderen Bereich der Website blättere.

Ich habe ein paar verschiedene Dateien.

Die Sitzung der Website wird in der Datei "config.php" gestartet.

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 hat den ersten Login-Bildschirm. Es prüft auch, ob jemand bereits angemeldet ist, indem eine Funktion in meiner USERS-Klasse aufgerufen wird.

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> 

ich in print_r setzen ($ _ SESSION), so konnte ich überprüfen, ob die Sitzung bei der Anmeldung neu gestartet wurde.

Wie auch immer, wenn Sie in das System angemeldet haben, es führt Sie auf die Homepage, "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> 

Beide Dateien aufrufen auf Funktionen, die in meiner User.php-Klassendatei definiert sind.

Klassen/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 = "[email protected]"; 
     $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 
    } 
?> 

glaube ich, die Ausgabe von irgendwo in der Redirect-Funktion stammt oder die Abmeldefunktion selbst, aber ich kann mich nicht für das Leben herauszufinden, warum. Die Sitzung wird nur in der Konfigurationsdatei gestartet, die überall enthalten ist. Das einzige Mal, dass ich der Site befehle, die Sitzung zu zerstören, ist die Logout-Funktion, die ich nur anrufe, wenn ich auf den Link "Abmelden" klicke auf der Startseite.

Ich würde wirklich jede Hilfe zu schätzen wissen, die Menschen bieten können. Ich habe viel länger ausgegeben, als ich zugeben möchte, dass ich versucht habe, das herauszufinden.

Vielen Dank!

UPDATE: Ich habe eine neue PHP-Datei erstellt und das Sitzungsupdate getestet. Die Sitzung wird in meiner Testdatei perfekt aktualisiert.

SessionTest.php

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

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

    //session_destroy(); 
?> 
+0

können Sie versuchen, ein anderes Verzeichnis mit drei anderen PHP-Dateien zu erstellen und suchen in Sie. Überträgt es die Sitzung? Ja? Das Problem liegt in Ihrem PHP. Nein? Vielleicht versuchen, PHP neu zu installieren ... –

+0

Sorry Koen, ich fürchte, ich folge nicht. Meinst du einen neuen Ordner mit PHP-Dateien erstellen und sehen, ob die Session-Variable dort funktioniert? –

+0

Ja, genau in der Tat –

Antwort

1

Nach einigem mehr in eingehenden Untersuchungen, ich habe mein Problem gefunden!

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

Dieser Code führt die Funktion aus, ob die Verknüpfung angeklickt ist oder nicht.

Ich habe das seit ein paar Verbesserungen repariert.

Erstens schalten Sie den obigen Code zu:

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

Zweitens in der __construct meiner Benutzerklasse:

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