April 7, 2013 asvignesh 0Comment

Best practises in checking codeigniter sessions

There are many practices in checking the session conditions for whether the user is logged in or not

Usually we check in the codeigniter controllers

function my_function() {
$user = $this->session->userdata(‘user_id’);
if (!isset($user)) {
$logged_in = false;
}
else {
$logged_in = true;
}
}

This 4-8 lines of code you need to check in every controller , So you can create a codeigniter library and call the library function in every controller , It is easy to code and also in modifying the code

 Create a my_library.php file in application/libraries

Copy the following code to my_library.php

class My_library extends Controller//CI_Controller
{
public function __construct()
{
parent::__construct();
}
public function is_logged_in()
{
$user = $this->session->userdata(‘user_id’);
return isset($user);
}
}

Create a controller x.php

Call the is_logged_in function using $this->is_logged_in();

class X extends My_library
{
public function __construct()
{
parent::__construct();
}
public function do_something()
{
if ($this->is_logged_in())
{
// The user is logged in
}
else{ //redirect to login page }
}
}

6+ years of experience in building data protection, copy data management and storage management applications, automation software and plugins for private and public clouds

Disclaimer :

This is a personal weblog. The opinions expressed here represent my own and not those of my employer. my thoughts and opinions change from time to time… This weblog is intended to provide a semi-permanent point in time snapshot and manifestation of the various memes running around my brain, and as such any thoughts and opinions expressed within out-of-date posts may not the same, nor even similar, to those I may hold today.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.