2016-09-28 86 views
2

我無法理解會話如何通過mvc與php協同工作。 我的意大利麪條代碼像魅力一樣工作,並在mvc中實現它給我帶來麻煩。我可以成功登錄。問題是爲登錄用戶保留一個會話,並顯示例如註銷按鈕。通過MVC的PHP會話

我登錄的看法:

<div class="container"> 
    <div class="login"><br> 
     <h4>Login</h4> 
     <?php 
      echo "<form method='POST' action='login-user.inc.php'> 
        <form class='login-inner'> 
         <input type='text' name='username' placeholder='Username' autocomplete='off' /><br /><br /> 
         <input type='password' name='password' placeholder='Password' /><br /><br />  
         <input class='button' type='submit' name='submit' value='Login' /> 
       </form> 
     </form>"; 
     ?> 
    </div> 
</div> 

登錄視圖經過登錄-user.inc.php:

<?php 
namespace View; 

use \Controller\SessionManager; 
use \Util\Util; 
use \Exceptions\CustomException; 

require_once 'mvc/Util/Util.php'; 
Util::initRequest(); 

$messageToUser = ""; 
$controller = ""; 

if(isset($_POST['username']) && isset($_POST['password']) && !isset($_POST[Util::USER_SESSION_NAME])){ 
    if(!empty($_POST['username']) && !empty($_POST['password'])){ 
     $username = htmlentities($_POST['username'], ENT_QUOTES); 
     $password = htmlentities($_POST['password'], ENT_QUOTES); 

     try{ 
      $controller = SessionManager::getController(); 
      $controller->loginUser($username, $password); 
      echo "<p class = 'positiveMessageBox'>You are logged in! :) Welcome!</p>"; 
     }catch(CustomException $ex){ 
      echo "<p class = 'warningMessageBox'>".$ex->getMessage()."</p>"; 
     }catch(\mysqli_sql_exception $ex){ 
      echo "<p class = 'negativeMessageBox'>An error in connection with database occurred! Please contact administration of this website.</p>"; 
     }finally{ 
      SessionManager::storeController($controller); 
     } 
    }else{ 
     echo "<p class = 'warningMessageBox'>Both username field and password field have to be filled! Try again!</p>"; 
    } 
} 

@$_GET['page'] = $_SESSION['pageId']; 
include Util::VIEWS_PATH."redirect.php"; 
?> 

我sessionhandler.php:

<?php 
namespace Controller; 

use Controller\Controller; 

/** 
* This class stores and retrieves session data 
* @package Controller 
*/ 
class SessionManager{ 
    const CONTROLLER_KEY = 'controller'; 
    const BROWSER_COMMENT_COUNT_KEY = 'browserCommentsCount'; 

    private function __construct(){} 

    /** 
    * This method stores controller instance in the current session 
    * @param \Controller\Controller $controller 
    */ 
    public static function storeController(Controller $controller){ 
     $_SESSION[self::CONTROLLER_KEY] = serialize($controller); 
    } 

    /** 
    * This method returns Controller instance 
    * If Controller instance do not exists then returns new instance 
    * @return \Controller\Controller 
    */ 
    public static function getController(){ 
     if(isset($_SESSION[self::CONTROLLER_KEY])) 
      return unserialize($_SESSION[self::CONTROLLER_KEY]); 
     else 
      return new Controller(); 
    } 
} 
?> 

我util,這是首先用session_start()初始化的:

<?php 
namespace Util; 

/** 
* Utility class 
* @package Util 
*/ 
final class Util{ 
    const VIEWS_PATH = 'src/view/'; 
    const CSS_PATH = 'src/css/'; 
    const IMG_PATH = 'src/img/'; 
    const USER_SESSION_NAME = 'username'; 

    private function __construct(){} 

    /** 
    * This method initialises autoload function and starts session 
    * This method should should be called first in any PHP page that receiving a HTTP request 
    */ 
    public static function initRequest(){ 
     \session_start(); 


     self::initAutoload(); 
    } 

    private static function initAutoload(){ 
     spl_autoload_register(function($class) { 
      require_once 'mvc/' . \str_replace('\\', '/', $class) . '.php'; 
     }); 
    } 
} 
?> 

這通過控制器等。這是成功登錄後會發生什麼。

public function login(LoginData $userLoginData){ 
    $userDAO = new UserDAO(); 

    if($userDAO->doUsernameExistInDB($userLoginData->getUsername())){ 
     if(password_verify($userLoginData->getPassword(), $userDAO->getUserPasswordFromDB($userLoginData->getUsername()))){ 
      session_regenerate_id(); 
      $_SESSION['username']; 
     }else 
      throw new CustomException("Password do not match with username you entered!"); 
    }else{ 
     throw new CustomException("We could not find the username you entered."); 
    } 
} 

最後是應該顯示註銷按鈕redirect.php:

我不知道爲什麼在登錄時會話未初始化它不斷告訴我,我當我已經擁有時,仍然可以登錄。我在這裏錯過了什麼?

回答

0

在您的登錄功能中,您似乎只需撥打$_SESSION['username']即可。

你不應該影響連接用戶的用戶名嗎?

然後,在你redirect.php,當你檢查\Util\Util::USER_SESSION_NAME相當於username,它必須是空的,然後總是顯示「登錄」按鈕。

希望這會有所幫助!

+0

謝謝你的回答!我認爲這實際上是問題。我能夠將登錄函數更改爲$ _SESSION ['username'] = $ _POST ['username'],這對應於輸入的用戶名。不過,我想知道如何能夠改變Util類中的常量。我希望能夠通過$ _POST訪問USER_SESSION_NAME,但無法訪問。有任何想法嗎? – Einstein

+0

好吧完美!請毫不猶豫地將您的問題設置爲已解決,謝謝! –

+0

在解決它以適合每個登錄用戶之前,我通過將常量「USER_SESSION_NAME」設置爲我當前使用的用戶登錄時進行調試,但仍然是同樣的問題。我將會話名稱更改爲我目前正在使用的用戶,現在它可以正常工作。我想我必須使用發佈的用戶名來實現會話名稱。謝謝您的幫助。 – Einstein