2015-11-20 87 views
0

我正在創建一個登錄檢查功能。但是我的兩個閃存數據信息設置不正確。Codeigniter 3登錄檢查功能不顯示正確的Flashdata消息

  1. 如果用戶已登錄,然後,如果會話過期,應該設置這個 閃存數據消息您的會話令牌已經過期!
  2. 如果用戶沒有登錄,並試圖用出來 記錄訪問控制器,那麼就應該設置此flashdata消息您需要登錄到 訪問這個網站!

由於某些原因,它總是顯示第二個flashdata消息。

問題:我該如何正確使用這兩個flashdata消息?

控制器:的login.php 功能:檢查

public function check() { 
    $uri_route = basename($this->router->directory) .'/'. $this->router->fetch_class(); 

    $route = isset($uri_route) ? $uri_route : ''; 

     $ignore = array(
      'common/login', 
      'common/forgotten', 
      'common/reset' 
     ); 

     if (!in_array($route, $ignore)) { 

      // $this->user->is_logged() returns the user id 

      if ($this->user->is_logged()) { 

       // $this->session->userdata('is_logged') returns true or false 

       if (!$this->session->userdata('is_logged')) { 

        // Redirects if the user is logged on and session has expired! 

        $this->session->set_flashdata('warning', 'Your session token has expired!'); 

        redirect('admin/common/login'); 
       } 

      } else { 

       $this->session->set_flashdata('warning', 'You need to login to access this site!'); 

       redirect('admin/common/login'); 

      } 
    } 

我笨通過鉤子運行功能這樣我就不必增加它的每一個控制器上。

$hook['pre_controller'] = array(
     'class' => 'Login', 
     'function' => 'check', 
     'filename' => 'Login.php', 
     'filepath' => 'modules/admin/controllers/common' 
); 
+0

請注意'$ uri_route'將因爲連接斜槓而被設置爲每個請求。其次,在您的描述之後,您似乎沒有登錄。因爲這是您在其他條件下獲得的。現在,您需要檢查和/或張貼代碼何時使用此方法獲得更多。 – Tpojka

回答

1

什麼是你想通過URI(檢查)實際上是檢查的一個很不錯的方法,你也應該包括登錄支票作爲一個構造函數不是單一..這裏是你的功能應該是什麼樣子:

function __construct() 
    { 
     parent::__construct(); 
     if (!$this->session->userdata('logged_in')) { 
     // Allow some methods? 
      $allowed = array(
       'some_method_in_this_controller', 
       'other_method_in_this_controller', 
      ); 
      if (!in_array($this->router->fetch_method(), $allowed) 
      { 
      redirect('login'); 
      } 
     } 
    } 
+0

感謝您的信息,但希望能夠設置相同的2閃存數據信息。 uri_route獲取文件夾和控制器名稱。我使用鉤子來運行該函數,因此不必在每個控制器上運行它,因爲我在主要問題上添加了鉤子部分。 – user4419336

+0

我可以從這裏看到你的代碼http://stackoverflow.com/questions/5920115/code-igniter-checking-if-user-logged-in-for-multiple-pages – user4419336