Search code examples
phpcodeigniterconstructorpreventdefault

Forcing CodeIgniter to send view and stop working


Hello I'm using inherited controllers. These are my controllers:

-baseAdminController:

<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');
class _BaseAdminController extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->library('session');

        $calledFunction= $this->router->fetch_method();
        if ($calledFunction!= 'loginView' && $calledFunction!= 'doLogin') {
            $this->checkSession();
        }
    }

    public function checkSession() {

        if ($this->session->userdata('loggedIn') == false) {
            $this->load->view('admin/loginView');
        }
    }
}

And my derived Admin Controllers:

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class AdminController extends _BaseAdminController {

    public function indexView() {
        $this->load->view('admin/indexView');
    }
}

When i'm tring to login, CodeIgniter shows me both admin/loginView and admin/indexView. Because i'm checking session status at constructing my derived controller. How can i prevent to loading second view?

Thank in advance..


Solution

  • To answer your question, you could have done the following into your checkSession method:

    public function checkSession() {
    
        if ($this->session->userdata('loggedIn') == false) {
            echo $this->load->view('admin/loginView', array(), TRUE);
            exit;
        }
    }
    

    Explanation: If you pass the third argument as TRUE, it will return the content of that file. Read ellislab.com for more info.