CodeIgniter Forums
I Can't Get My Sessions To Work Right - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived General Discussion (https://forum.codeigniter.com/forum-21.html)
+--- Thread: I Can't Get My Sessions To Work Right (/thread-61219.html)

Pages: 1 2


I Can't Get My Sessions To Work Right - El Forum - 10-18-2014

[eluser]ShoeLace1291[/eluser]
I am having loads of trouble getting my sessions to work right with my CodeIgniter application. I can log in once, but then after 5 minutes I get logged out. When I go to log back in again, my script says I am already logged into a member account and only on the login page, my account toolbar displays that I am logged in. Then I go back to the home page and I'm "logged out" again. I cannot access any "member only" content.

Through a core extension of the controller class that gets the current user's information I use $this->user throughout the app controllers to display the user's information. It could also be something with my config but I thought I got that straightened out... maybe not... who knows. So here's my code:


I Can't Get My Sessions To Work Right - El Forum - 10-18-2014

[eluser]ShoeLace1291[/eluser]
Controller extension:
Code:
<?php

class MY_Controller extends CI_Controller {
    
    var $user = array();
    
    function __construct(){
        
        parent::__construct();
        $this->load->model('member');
        
     if(!$this->config->item('global_maintenance')){
      
      if($this->config->item('beta_mode')){
        
          $this->load->model('_beta');
          
          if($this->uri->uri_string() != 'beta/signup'){
          
           $this->_beta->get_user($this->input->ip_address());
           if($this->_beta->error == NULL){
            
            $this->betaUser = $this->_beta->info;
            
           } else {
            
            redirect('beta/signup');
            
           }
          
          }
          
      }
      
      $this->member->get_info($this->session->userdata('member_id'));
      if($this->member->error == NULL){
      
       $this->user = $this->member->info;
      
      }            
      
      
     } else {
      
       die('BaseCMD is currently down for routine maintenance.  Please try again later!');
      
      }
    
}
    
}



I Can't Get My Sessions To Work Right - El Forum - 10-18-2014

[eluser]ShoeLace1291[/eluser]
The member model:
Code:
<?php

class Member extends CI_Model {

    var $info = array();
    var $error = NULL;
    var $activation_code = '';
    var $id = 0;
    
    function __construct(){
        
        parent::__construct();
        $this->error = NULL;
        
        
    }
    
    function default_info(){
        
        $info = array(
                'id' => 0,
                'display_name' => 'Guest',
                'email_address' => '',
                'password' => '',
                'status' => 0,
                'activation_code' => '',
                'location' => '',
                'date_joined' => '',
                'gender' => '',
                'results_per_page' => 10,
                'admin_emails' => FALSE,
                'member_emails' => FALSE,
                'team' => array('id' => 0),
                'perms' => array(),
                'group' => array('id' => 0),
                'stats' => array(),
                'signature' => '',
                'last_active' => 0,
                'last_forum_visit' => 0,
                'member_profile' => 'Guest',
                'date_of_birth' => '',
                'gender' => '',
                'profile_banner' => '',
                'avatar' => array('url' => '')
            );
        
        return $info;
    
    }
    
    public function get_info($criteria){
        
        $where = (is_numeric($criteria)) ? "WHERE member_id = ".$criteria : "WHERE email_address = '".$criteria."'";        
        
        $query_member = "
            SELECT
                m.member_id, m.display_name, m.email_address, m.group_id, m.status, m.activation_code, UNIX_TIMESTAMP(m.date_joined) AS date_joined,
                m.gender, m.location, m.biography, m.mantra, m.birth_date, m.results_per_page, m.admin_emails, m.member_emails,
                m.last_active, m.avatar_id, m.banner_id, m.signature, m.newsletter_subscription, m.recruiting_status,
                m.facebook_username, m.website, m.steam_username, m.xboxlive_gamertag, m.psn_id,
                g.group_id, g.title, g.description,
                a.attachment_id, a.file_name,      
                f.message_id, f.author_id, COUNT(f.message_id) AS forum_count    
            FROM members AS m
            LEFT JOIN member_groups AS g ON (m.group_id = g.group_id)  
            LEFT JOIN attachments AS a ON (m.attachment_id = a.attachment_id)        
            LEFT JOIN forum_messages AS f ON (m.member_id = f.author_id)
            ".$where."
            GROUP BY m.member_id
            LIMIT 1";          
            
        if($query_member = $this->db->query($query_member)){
        
            if($query_member->num_rows() > 0){
                
                $member = $query_member->row_array();
                
                $member_id = $member['member_id'];
                    
                    /* Determine if the user is already friends with the member... */
                    $this->db->select('request_id, author_id, recipient_id, status');
                    $this->db->from('member_requests');
                    $this->db->where('status', '1');
                    $this->db->where('author_id', $this->user['id']);
                    $this->db->where('recipient_id', $member_id);
                    $this->db->or_where('author_id', $member_id);
                    $this->db->where('recipient_id', $this->user['id']);
                        
                    if($query_friend = $this->db->get()){
                            
                        if($query_friend->num_rows() > 0){
                                
                            $friend_status = TRUE;
                                
                        } else {
                                
                            $friend_status = FALSE;
                                
                        }
                            
                    }
                    
                 $info = array(
                    'id' => $member['member_id'],
                    'display_name' => $member['display_name'],
                    'email_address' => $member['email_address'],
                    'status' => ($member['status'] == 0) ? FALSE : TRUE,
                    'activation_code' => $member['activation_code'],
                    'location' => $member['location'],
                    'date_joined' => date('M jS, Y', $member['date_joined']),
                    'gender' => ($member['gender'] == 0) ? 'Male' : 'Female',
                    'results_per_page' => $member['results_per_page'],
                    'admin_emails' => ($member['admin_emails'] == 0) ? FALSE : TRUE,
                    'member_emails' => ($member['member_emails'] == 0) ? FALSE : TRUE,
                    'group' => array(
                     'id' => $member['group_id'],
                     'title' => $member['title'],
                     'description' => $member['description']
                     ),
                    'signature' => $member['signature'],
                    'last_active' => strtotime($member['last_active']),
                    'member_profile' => anchor('members/'.url_title($member['display_name']).'/'.$member['member_id'], $member['display_name']),
                    'newsletter' => ($member['newsletter_subscription'] == 1) ? TRUE : FALSE,
                    'date_of_birth' => date('M jS, Y', strtotime($member['birth_date'])),
                    'birth_date' => date('Y-m-d', strtotime($member['birth_date'])),
                    'age' => floor((time() - strtotime($member['birth_date'])) / (60 * 60 * 24 * 365)),
                    'gender' => $member['gender'],
                    'biography' => $member['biography'],
                    'banner' => NULL,
                    'mantra' => $member['mantra'],



I Can't Get My Sessions To Work Right - El Forum - 10-18-2014

[eluser]ShoeLace1291[/eluser]
member model continued...
Code:
'contact' => array(
                        'email' => ($member['member_emails'] == '1') ? $member['email_address'] : NULL,
                        'website' => ($member['website'] != '') ? $member['website'] : NULL,
                        'facebook' => ($member['facebook_username'] != '') ? 'http://www.facebook.com/'.$member['facebook_username'] : NULL,
                        'steam' => ($member['steam_username'] != '') ? 'http://www.steamcommunity.com/id/'.$member['steam_username'] : NULL,                        
                        ),
                    'gaming' => array(
                     'xboxlive' => $member['xboxlive_gamertag'],
                     'psn' => $member['psn_id'],
                     'steam' => $member['steam_username']
                     ),
                    'friend_status' => $friend_status,
                    'statistics' => array('post_count' => $member['forum_count']),
                    'avatar' => array(
                     'attachment_id' => $member['attachment_id'],
                     'url' => base_url('attachments/'.$member['file_name'])
                     ),
                    'banner' => $banner,
                    'friends' => $this->friend_results($member_id)
                    );
                        
                
                show_error(var_dump($info));
                //$info['friend_results'] = $this->friend_results($member_id);
                
                $this->info = $info;
                
            } else {
                
                $this->info = $this->default_info();
                
            }
            
        }
        
    }

  public function login($remember = FALSE){
        
        $this->db->select('*');
        $this->db->where('email_address', $this->input->post('email_address'));
        $query = $this->db->get('members');
        
        if($query->num_rows() > 0){
            
            $member = $query->row_array();
            
            if(sha1($this->input->post('password')) == $member['password']){
                
                if($member['status'] > 0){
                
                 $this->session->set_userdata('member_id', $member['member_id']);
                    
                    $data = array(
                        'last_active' => time()
                    );
                    
                    $this->db->where('member_id', $member['member_id']);
                    if(!$this->db->update('members', $data)){
                        
                        $this->error = $this->db->_error_message();
                        
                    }
                    
                } else {
                    
                    $this->error = 'You haven\'t validated your email address.  We sent an email message to the address that you provided when you created your account.  Follow the directions in this message to validate your email address.';
                    
                }
                
            } else {
                
                $this->error = 'The password you entered does not match the one that we have on record for your account.';
                
            }
            
        } else {
            
            $this->error = 'The email address \''.$this->input->post('email_address').'\' does not match any accounts that we have on record.';
            
        }
        
    }[



I Can't Get My Sessions To Work Right - El Forum - 10-18-2014

[eluser]ShoeLace1291[/eluser]
The login controller
Code:
<?php

class Login extends MY_Controller {
    
    function __construct(){
        
        parent::__construct();
        
    }
    
    function index(){                
        
        if($this->user['id'] == 0){
            
            $this->load->library('form_validation');
            
            $this->form_validation->set_error_delimiters('<span class="error">', '</span>');
            
            if($this->form_validation->run('signin') == FALSE){
            
             $this->template->overall_header("Member Login");
                
                $data = array(
                    'breadcrumbs' => $this->template->breadcrumbs(
                                        array(
                                            'Home' => 'home',
                                            'Members' => 'members',
                                            'Login' => 'members/login'
                                        )
                    )
                );
                
                $this->load->view('members/login_body', $data);
                
            } else {
                
                $remember = ($this->input->post('remember') == '1') ? TRUE : FALSE;
                $this->member->login($remember);
                
                if($this->member->error == NULL){
                
                 $this->template->overall_header("Login Successful");
                    
                    $data = array(
                       'error_title' => "Login Success",
                       'error_message' => "You are now logged in and will be redirected to your account page.",
                       'redirect' => 'members/login'
                       );
                      
                   $this->load->view('error_body', $data);
                    
                } else {
                
                 $this->template->overall_header("Login Failed");
                    
                   $data = array(
                       'error_title' => "Login Failed",
                       'error_message' => $this->member->error,
                       'redirect' => 'members/login'
                       );
                      
                   $this->load->view('error_body', $data);
                    
                }
                
            }
            
        } else {
            
            $this->template->overall_header("Oops!");
                    
                    $data = array(
                       'error_title' => "Oops!",
                       'error_message' => "You are already logged into a member account!",
                       'redirect' => 'members/account'
                       );
                      
                   $this->load->view('error_body', $data);
            
        }
        
    }



I Can't Get My Sessions To Work Right - El Forum - 10-18-2014

[eluser]ShoeLace1291[/eluser]
And finally, the config
Code:
$config['sess_cookie_name']  = 'basecommand_frontend';
$config['sess_expiration']  = 2592000; /* 30 Days */
$config['sess_expire_on_close'] = FALSE;
$config['sess_encrypt_cookie'] = FALSE;
$config['sess_use_database'] = TRUE;
$config['sess_table_name']  = 'ci_sessions';
$config['sess_match_ip']  = FALSE;
$config['sess_match_useragent'] = TRUE;
$config['sess_time_to_update'] = 300;

$config['cookie_prefix'] = "";
$config['cookie_domain'] = "basecommand.com";
$config['cookie_path']  = "/";
$config['cookie_secure'] = FALSE;



I Can't Get My Sessions To Work Right - El Forum - 10-19-2014

[eluser]InsiteFX[/eluser]
If your using Internet Explorer for a web browser then you need to remove the under score from the cookie name.

Code:
$config['sess_cookie_name']  = 'basecommandfrontend';



I Can't Get My Sessions To Work Right - El Forum - 10-20-2014

[eluser]Narf[/eluser]
[quote author="InsiteFX" date="1413720698"]If your using Internet Explorer for a web browser then you need to remove the under score from the cookie name.

Code:
$config['sess_cookie_name']  = 'basecommandfrontend';
[/quote]

Not true.
If that fixes it, then adding another underscore will also fix it.


I Can't Get My Sessions To Work Right - El Forum - 10-20-2014

[eluser]InsiteFX[/eluser]
IE Cookies

Internet Explorer doe's not follow the RFC specs.



I Can't Get My Sessions To Work Right - El Forum - 10-20-2014

[eluser]Narf[/eluser]
[quote author="InsiteFX" date="1413840160"]IE Cookies

Internet Explorer doe's not follow the RFC specs.
[/quote]

Yet, that has nothing to do with underscores in cookie names. I've seen this argument before, but it's simply not relevant.

msdn.com itself sends cookies with underscores in their name and if you are referring to this:

Quote:Q5: IE won’t set a cookie when the hostname/domain contains an underscore?

... note that it's about hostname/domain, not the cookie name.

It's a myth.