Radu033 Radu033 - 24 days ago 12
PHP Question

Codeigniter show controller if session exists

I'm new to codeigniter and learn it, please don't downvote the question if you think it's stupid, rather help me :)

I got 2 controllers, 1st one called main and responds for user registration / login the second one is called todo and shows a todo list.

Now if I access localhost/list my website opens the page, where do I write the session logic to test if user is logged in?

My controller todo

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

class Lists extends CI_Controller {

public function index()
{
$this->load->view('lists');}
}


How do I display it using the session:

if($this->session->userdata('is_logged_in') == 1)


Or do I have to put the session logic before each function?

Thanks :)

Answer

You put the session $this->session->userdata('is_logged_in') condition in __construct()

Like this :

<?php
class Lists extends CI_Controller {

    public function __construct() {
        parent::__construct();
        if($this->session->userdata('is_logged_in') != 1) { 
            //redirect code here
        }
    }

    public function index() {
        $this->load->view('lists');}
    }
}
Comments