2016-12-05 13 views
0

私のウェブサイトで$ _SESSION変数に問題があります。何らかの理由で、私はページをリロードするたびに、または私がウェブサイトの別のセクションを参照すると、自分自身をリセットするように見えます。

私はいくつかの異なるファイルを持っています。

サイトのセッションは、「config.php」ファイルで開始されます。

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は、最初のログイン画面を持っています。また、USERSクラスの関数を呼び出して誰かがすでにログインしているかどうかを確認します。

の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> 

私がしますprint_rで($ _ SESSION)を入れたので、私はセッションがログイン時に再起動されたことを確認できました。とにかく

、あなたがシステムにログインしたら、それは "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> 

どちらが呼び出します私のuser.phpクラスファイルに定義された関数

クラス/ 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 
    } 
?> 

私は、問題は、リダイレクト機能やログアウト機能自体のどこかから茎が、私は私の人生のために、なぜを把握することはできませんと信じています。セッションはコンフィグレーションファイルでのみ開始され、必要な場所に含まれています。セッションを破棄するようにサイトに指示する唯一の時間は、ログアウト機能です。ログアウト機能を使用しています。ホームページに

私は本当に人々が提供することができるこの上の任意のヘルプに感謝したいと思います。私はこれを理解しようとするよりもはるかに長い時間を過ごしました。

多くの感謝!

更新:私は新しいPHPファイルを作成し、セッションの更新をテストしました。セッションは私のテストファイルで完全に更新されます。いくつかのより詳細な調査の後

sessionTest.php

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

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

    //session_destroy(); 
?> 
+0

あなたは3つの他のPHPファイルを別のディレクトリを作成し、中を見てみてくださいそれら。セッションを転送しますか?はい?問題はあなたのPHPにあります。いいえ?たぶん、PHPを再インストールしようとしました... –

+0

申し訳ありませんが、私はフォローしません。 phpファイルを含む新しいフォルダを作成し、セッション変数がそこで動作するかどうかを確認することを意味しますか? –

+0

はい、まさに実際に –

答えて

1

、私は私の問題を発見しました!

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

このコードは、リンクがクリックされたかどうかに関係なく機能を実行します。

私はそれ以来、これをいくつか調整して修復しました。

まず、に上記のコードを切り替えます。第二に

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

、私のユーザークラスの__constructに:

if(isset($_GET['logout']) && $_GET['logout'] == "callLogoutFunction") 
{ 
    $this->logout(); 
} 
関連する問題