CodeIgniter Forums
Session Not Working Properly in _construct - 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: Session Not Working Properly in _construct (/showthread.php?tid=61061)



Session Not Working Properly in _construct - El Forum - 09-10-2014

[eluser]xitclub[/eluser]
Hi,
I am having a problem with sessions, its not working properly in one of Controller. Let me explain with code

Controller

Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class User extends CI_Controller {

function __construct(){
        parent::__construct();
        $this->check_isvalidated();
    }
public function index()
{
  $this->load->view('inc/above_header');
  $this->load->view('inc/header');
  $this->load->view('user_dashboard');
  $this->load->view('inc/footer');
  $this->load->view('inc/below_footer');
}
function dashboard()
{
  $this->load->view('inc/above_header');
  $this->load->view('inc/header');
  $this->load->view('user_dashboard');
  $this->load->view('inc/footer');
  $this->load->view('inc/below_footer');
}

  private function check_isvalidated(){
  $user_id = $this->session->userdata('user_id');
  $validated = $this->session->userdata('validated');
        if(!isset($validated) && $validated =="" && !isset($user_id) && $user_id ==""){
            redirect('login');
        }
    }
}

Now the problem is it should redirect user to login page if user not logged in, but instead its showing user the content.


Session Not Working Properly in _construct - El Forum - 09-10-2014

[eluser]jcorry[/eluser]
$this->session->userdata('validated') will return FALSE if it doesn't find a 'validated' key in the userdata array.

So your conditional could be:

if(!$validated || $user_id < 1) //assumes $user_id is an integer

I changed the && to || figuring you'd want to redirect on either condition.


Session Not Working Properly in _construct - El Forum - 09-10-2014

[eluser]CroNiX[/eluser]
@jcorry I'd use tripple operator to check whether the value exists in session so you actually check for boolean false, because many times 0 is an actual legitimate value in session so your (!) check wouldn't allow it.
Code:
if ($validated !== FALSE)



Session Not Working Properly in _construct - El Forum - 09-10-2014

[eluser]xitclub[/eluser]
Great Thanks guys, it solved my problem Smile