Clain Dsilva
Clain Dsilva

Reputation: 1651

How to create a common function in codeigniter for checking if session exist?

I am creating an application where in users have to login to access various modules. I need to check if the user session exist before providing access to each module.

Now I am checking session like this in each function / module / controller to avoid unauthorized access.

if($this->session->userdata('userId')!=''){
   do something;  }

Is there a better way to do this? can I have common function similar like

sessionExist();

such that it can be called from any module / controller / function which is common to the whole project?

If so where should I write this common function such that it can be called from anywhere.

Upvotes: 4

Views: 11439

Answers (5)

Pramod Jain
Pramod Jain

Reputation: 462

if ( ! function_exists('sessionExist'))
{
function sessionExist(){
$CI =& get_instance();
$userId = $CI->session->userdata('userId');
if(empty($userId)){
redirect(base_url('login'));
}else{
return (bool)$userId;
}
}
}

Upvotes: 0

leonardeveloper
leonardeveloper

Reputation: 1853

In your model where you set your session:

   $data = array(
      'sid' =>$this->input->post('sid'),
       'is_logged_in' => true,
      );
   $this->session->set_userdata($data);

And in your function / module / controller:

    function __construct(){
    $this->is_logged_in()
    }

   function is_logged_in(){
    $is_logged_in =$this->session->userdata('is_logged_in');

    if(!isset($is_logged_in) || $is_logged_in != TRUE)
    {
        echo 'You dont have permission to acces this page';
        die();
    }

Upvotes: 0

igasparetto
igasparetto

Reputation: 1146

You want a helper function, here it is:

if ( ! function_exists('sessionExist'))
{
    function sessionExist(){
        $CI =& get_instance();
        return (bool) $CI->session->userdata('userId');
    }
}

Save the file in application/helpers/ and include it your application/config/autoload.php file:

$autoload['helper'] = array('my_helper_file');

Upvotes: 5

egig
egig

Reputation: 4430

If it's class, then create library. if only function then create helper, and then autoload them so it can be called anywhare.

Upvotes: 6

Bora
Bora

Reputation: 10717

You can create a function in library that you created it or another library

ex: application/libraries/Common.php

public function logged_in()
{    
   return (bool) $this->session->userdata('userId');
}

Using like this:

if ($this->common->logged_in()) {
   // User logged
} else {
   // User not logged
}

Upvotes: 1

Related Questions