2015-02-27 11 views
0

Я поставил login контроллер в качестве контроллера по умолчаниюпроверка сессии не работает должным образом - CodeIgniter

В моей модели Membership, у меня есть функция checkLogin(), которая возвращает true, если сеанс имеет действительные данные.

Метод checkLogin() работает нормально.

Я вызываю метод checkLogin() в конструкторе, как показано ниже.

Метод checkLogin() работает нормально, но не уверен, почему при загрузке Login/postSignin метод не перенаправляется на приложение.

P.S: После обновления страницы она автоматически перенаправляется. Поэтому я уверен, что в логике есть некоторая ошибка.

Любая помощь будет оценена

<?php 
#File : ../controllers/Login.php 

class Login extends CI_Controller{ 

    #Global Variables and Models to be loaded are initiated here 
    public function __construct(){ 
     parent::__construct(); 
     /* 
     | 
     | Load the Following Models 
     | 1.Membership 
     | 
     */ 
     $this->load->model('Membership'); 
     #Check for Login details in the cookie 
     #If checkLogin() returns true, it indicates that the user has logged in already 
     if($this->Membership->checkLogin()) 
     { 
      #redirect to ../controllers/Application Controller 
      Redirect('Application'); 
     } 
    } 
    #Loads the Basic Header | Footer | Sidebar && a Specific view->Signin 
    public function index(){ 
     $this->load->view('include/Header'); 
     $this->load->view('include/SideBar'); 
     $this->load->view('Signin'); 
     $this->load->view('include/Footer'); 
    } 
    /* 
    | 
    | 
    | 
    */ 
    public function postSignin(){ 
     #Setting custom delimiters 
     $this->form_validation->set_error_delimiters('<div class="form-group col-sm-8 center-block form-error bg-danger text-danger text-center">', '</div>'); 
     /* 
     | 
     | ** Rules ** 
     | Email  -> required, Valid email 
     | Password -> required, minimum length=5, maximum length=12 
     */  
     $this->form_validation->set_rules('emailid','Email','required|valid_email'); 
     $this->form_validation->set_rules('password','password','required|min_length[5]|max_length[12]|'); 
     #if the validation failes 
     if ($this->form_validation->run() == FALSE) 
     { 
      #load the Header | Footer | Sidebar | Signin views again 
      $this->load->view('include/Header'); 
      $this->load->view('include/SideBar'); 
      $this->load->view('Signin'); 
      $this->load->view('include/Footer'); 
     } 
     else 
     { 
      #If checkCredentials() method returns true, it indicates a valid login 
      if($this->Membership->checkCredentials()) 
      { 
       $emailid=$this->input->post('emailid'); 

       #Create an array to store all the necessary details 
       $session_data=array(
         'user_id'=>$this->Membership->getUserId($emailid), 
         'email'=>$emailid, 
         'first_name'=>$this->Membership->getFirstName($emailid), 
         'last_name'=>$this->Membership->getLastName($emailid), 
        ); 
       #Set the session data using array formed above 
       $this->session->set_userdata($session_data); 
       #Redirect to the next controller '../controllers/Application' 
       Redirect('Application');   
      } 
      #If checkCredentials() returns false, load views and display appropriate message 
      else 
      { 
       #set login-status to 0 
       $data['login_status']=0; 
       #load the Header | Footer | Sidebar | Signin views again 
       $this->load->view('include/Header'); 
       $this->load->view('include/SideBar'); 
       $this->load->view('Signin',$data); 
       $this->load->view('include/Footer'); 
      } 
     }  
    } 
} 
?> 
+0

Почему вы не можете загрузить изображение после успешного входа? как $ this-> load-> view ('view_name_here'); – CodeWithCoffee

+0

Потому что мне нужен другой контроллер, чтобы взять основное приложение. Если возможно, знаете ли вы конкретный способ перехода от одного контроллера к следующему? –

+0

перенаправление должно работать на самом деле. Не уверен, но можете ли вы, пожалуйста, изменить Перенаправление на перенаправление и сделать R маленьким вместо шапки? – CodeWithCoffee

ответ

0

Cache был виновником здесь! Я отключил их. Теперь он не возвращается. Спасибо, ребята, за вашу помощь.

$this->output->set_header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT"); 
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate"); 
$this->output->set_header("Cache-Control: post-check=0, pre-check=0", false); 
$this->output->set_header("Pragma: no-cache"); 
0

Вы можете сделать контроллер ядра, который будет обрабатывать эту часть кода, проверка состояния входа. Чем вы можете расширить этот контроллер с помощью любого контроллера приложения, которому требуется проверка входа в систему.

<?php if (! defined('BASEPATH')) exit('No direct access allowed'); 
//this is in APPPATH . 'core/' 
class MY_Logincheck extends CI_Controller 
{ 
    public function __construct() 
    { 
    parent::__construct(); 
    } 

    public function index() 
    { 
    /* 
    | 
    | Load the Following Models 
    | 1.Membership 
    | 
    */ 
    $this->load->model('Membership'); 
    #Check for Login details in the cookie 
    #If checkLogin() returns true, it indicates that the user has logged in already 
    if(! $this->Membership->checkLogin()) { 
     #redirect to ../controllers/Application Controller 
     redirect('login', 'refresh'); 
     exit();// check switched to be firstly seen if not login passed 
    } 
    } 
} 

Чем

<?php if (! defined('BASEPATH')) exit('No direct access allowed'); 

class Application extends MY_Logincheck 
{ 
    public function __construct() 
    { 
    parent::__construct(); 
    } 

    public function index() 
    { 
    // some code related to application 
    } 
} 

Несколько вещей, которые нужно рассмотреть. 1.) Я не уверен, что вы получите хорошую маршрутизацию к контроллеру приложений без кода файла .htaccess. 2.) Проверьте некоторые библиотеки, такие как Ion_Auth от Ben Edmund для CI, это упростит ситуацию. 3.) Дважды проверьте, загружены ли все необходимые помощники и библиотеки. 4.) Без кода модели я не могу сказать больше.

+0

Спасибо :) Я обязательно это проверю :), но я хочу, чтобы приложение также расширило CI_Controller? можно ли расширять «приложение» из двух классов? –

+0

'class Some_class extends CI_Controller {} class Application extends Some_class {}' У вас уже есть наследование от CI_Controller. Проверьте документацию PHP для этого. [Нажмите] (http://php.net/manual/en/keyword.extends.php). [Два] (http://php.net/manual/en/reflection.extending.php). [Три] (http://php.net/manual/en/language.oop5.inheritance.php). – Tpojka

Смежные вопросы