CodeIgniter Forums
storing db info in session - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forumdisplay.php?fid=20)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forumdisplay.php?fid=23)
+--- Thread: storing db info in session (/showthread.php?tid=51011)



storing db info in session - El Forum - 04-17-2012

[eluser]brian88[/eluser]
is storing database info in the session a good idea?

Code:
$data = array(
    'logged_in' => true,
    'userInfo' => $this->login_mod->getUserByEmail( $this->input->post('email') )
);
$this->session->set_userdata($data);

Now I have all the users info but inside the session, which I think is too long of code
Code:
<?php echo $this->session->userdata('userInfo')->name; ?>

Is this good practice? Is there any downsides to this or can the session somehow break?
Also, is it bad to store a sha1() password in it too?


storing db info in session - El Forum - 04-18-2012

[eluser]gRoberts[/eluser]
I wouldn't store the actual user object within the session, instead I would only store the UserID and then when you need to access it, look it up.

I do this using Static functions, i.e.

Code:
<?
public class Core
{
  public static $CI = null;
  public static CI()
  {
   if(self::$CI === null)
   {
    self::$CI =& get_instance();
   }
   return self::$CI;
  }
}

public class Security
{
  public static $UserID = null;
  public static function GetUserID()
  {
   if(self::$UserID === null)
   {
    $CI->load->library('session');
    $UID = $CI->session->userdata('UserID');
    if($UID !== false)
    {
     self::$UserID = $UserID;
    }
   }
   return self::$UserID;
  }

  public static $CurrentUser = null;
  public static GetUser()
  {
   $UserID = Security::GetUserID();
   if($UserID === null)
    return null;

   if(self::$CurrentUser === null)
   {
    $CI->load->model('User_model');
    self::$CurrentUser = $CI->user_model->GetSingle($UserID);
   }
   return self::$CurrentUser;
  }
}
?>

I done it like this, because in some cases, during one page execution, I might need to get the UserID or User object more than once. If I do, rather than creating multiple executions etc, I just call

Code:
$UserID = Security::GetUserID();

or

Code:
<h1>Hello &lt;?= Security::GetUser()->Forename; ?&gt;</h1>

You can also use GetUserID to check if the user is logged in, which you'd obviously need to do before calling GetUser()->Forename.

HTH