I would use a different approach, as @atno said: you are using the MVC pattern, so doing such checks in your view is logically incorrect, and also against the DRY approach.
I would do a controller check using the function that I have in the model and load the appropriate view according to the results:
class Mycontroller extends CI_Controller { function index() //just an example { $this->load->model('mymodel'); if($this->mymodel->is_logged()) { $this->load->view('ok_page'); } else { $this->load->view('not_logged_view');
In your model:
function is_logged() { $logged = $this->session->userdata('user_id'); if ($logged) { return TRUE; } else { return FALSE; } }
If necessary, you need to do it programmatically, for each controller method (for example, to check the login), you can check inside the constructor:
function __construct() { parent::__construct();
Thus, you will have a check before calling any controller method, that is, when initializing the controllers.
UPDATE : using the model may be redundant here, you can just check what $ this-> session returns:
function index() { // or mypage() or whatever if($this->session->user_data('user_id')) { $this->load->view('ok_page'); } else { $this->load->view('not_ok_page'); } }
source share