Session Validation best practices in Php Codeigniter

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 }
}
}

Leave a Reply

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

Discover more from

Subscribe now to keep reading and get access to the full archive.

Continue reading