Welcome Guest, Not a member yet? Register   Sign In
storing db info in session
#1

[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?
#2

[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




Theme © iAndrew 2016 - Forum software by © MyBB