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 }
}
}
Default image
Vignesh A Sathiyanantham
AWS Certified developer with 8 years of extensive experience working for Cloud and Datacenter solutions and leading a small team in a lean startup based on Bangalore, India

Leave a Reply

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