CodeIgniter_Learner
CodeIgniter_Learner

Reputation: 527

Codeigniter 3 Session Data On Other Pages While User Logged In

Got this question here (sorry for being stupid), Just started with Codeigniter recently.

I have a login-system working fine. I tried to go to homepage while logged in with code on index-header.php:

<?php 
if( !isset($_SESSION) ){
    echo '<a href="login" class="popupbox">Login</a>';
} else {
    echo '<a href="dashboard/logout">Log Out</a>';
}
?>

And on main_view.php (homepage controller)

public function __construct() {
    parent::__construct();
    $this->load->library('session');
}

public function index() {
    if($this->session->userdata('is_logged_in')){
        $data['title'] = "Home";
        $this->load->view('headfoot/header-main',$data);
        $this->load->view('main_view');
        $this->load->view('headfoot/footer-main');
    } else {
        $data['title'] = "Home";
        $this->load->view('headfoot/header-main',$data);
        $this->load->view('main_view');
        $this->load->view('headfoot/footer-main');
    }
}
}

Now, if I click logout from homepage while still logged in, it disconnects the session fine but doesn't change text back to "Login" in homepage after refresh. In other words, it always shows text as "Logout" whether or not user is logged in.

dashboard.php (controller)

public function logout() {
    $this->session->sess_destroy();
    $data['title'] = "Logged out";
    $data['logout_msg'] = "You have successfully logged out.";
    $this->load->view('headfoot/header-login',$data);
    $this->load->view('admin/login', $data);
    $this->load->view('headfoot/footer-login');
}

Is it a good practice to create is_logged_in.php a separate file? If yes then how to link sessions to it?

Upvotes: 0

Views: 1548

Answers (2)

Dray
Dray

Reputation: 887

change this:

 <?php 
 if( !isset($_SESSION) ){

to:

<?php if($this->session->userdata('username') == null ){

i'm using 'username' here by assuming you have set username as session data when you allow user to log in.

Upvotes: 2

Deniz B.
Deniz B.

Reputation: 2562

Use $this->session->sess_destroy(); to kill session. Check this URL. Kill session by controller then use redirect.

By the way, create a file under application/core folder called MY_Controller.php and make your session things on it. If you want to learn more just google it.

Upvotes: 0

Related Questions