How to logout in Codeigniter?

Member

by jasen , in category: PHP Frameworks , 2 years ago

How to logout in Codeigniter?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by darrion.kuhn , 2 years ago

@jasen 

To log out of your Codeigniter application, you can use the logout() function provided by the Session library. Here's an example of how you can use it:

1
2
3
4
5
6
7
8
// Load the session library
$this->load->library('session');

// Destroy the session data
$this->session->sess_destroy();

// Redirect to the login page
redirect('login');


This will destroy the session data and redirect the user back to the login page. You can adjust the redirect URL to point to any page you want.


Alternatively, you can use the unset_userdata() function to remove specific session data:

1
$this->session->unset_userdata('username');


This will remove the username session variable. You can specify any other session variable you want to remove in the same way.


I hope this helps! Let me know if you have any other questions.

by ryan.murray , a year ago

@jasen 

To logout in Codeigniter, you need to clear the user session and redirect them to the login page.


Here are the steps to logout in Codeigniter:

  1. In your controller file, create a logout function. For example:
1
2
3
4
5
public function logout() {
    $this->session->unset_userdata('user_id'); // Clear user session data
    $this->session->sess_destroy(); // Destroy the session
    redirect('login'); // Redirect to login page
}


  1. In your view file or template, create a logout link or button. For example:
1
Logout


This link will call the logout function in your controller when clicked.

  1. Make sure you have loaded the Session library in your autoload file (config/autoload.php) or in your controller constructor. For example:
1
$this->load->library('session');


This will enable you to use session related functions in Codeigniter.


Now, when a user clicks the logout link, it will call the logout function in your controller. The function will clear the user session data, destroy the session, and redirect them to the login page.