CodeIgniter Forums
Prevent access to pages if session is not set - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: General Help (https://forum.codeigniter.com/forumdisplay.php?fid=24)
+--- Thread: Prevent access to pages if session is not set (/showthread.php?tid=68612)



Prevent access to pages if session is not set - nullstrike - 08-04-2017

Is there a way that redirects user to login page if he tries to access a page without logging in.

I have my attempt on doing this but to no avail I failed 

Code:
class Navigation extends CI_Controller
{
protected $data;
public function __construct()
{
parent::__construct();
$this->load->model('user_model'); 
$this->load->helper('url');
if (!$this->session->userdata('userID') === TRUE){
header('Location: index.php');
}
}

/*
*Load the index page
*/
public function index()
{
$this->load->view('index');
}
    

    public function edit(){
        $this->page('dashboard/change_pass','dashboard/change_pass');
    }
/*
*Load the admin dashboard page
*/
public function dashboard()
{
$this->page('dashboard/index');



RE: Prevent access to pages if session is not set - neuron - 08-04-2017

Code:
class Navigation extends CI_Controller
{
protected $data;
public function __construct()
{
parent::__construct();
if (!isset($this->session->userdata['userID'])){
redirect('login');
}
$this->load->model('user_model'); 
$this->load->helper('url');

}



RE: Prevent access to pages if session is not set - skunkbad - 08-04-2017

If you need this to be secure, you should use one of the existing auth libraries. If you don't care about getting hacked and nothing matters, then by all means keep going down that road. It's not that the sessions library is totally hackable, but there's a lot to think about when doing authentication, and it's clear that you've not considered many of the things that would make authentication secure.


RE: Prevent access to pages if session is not set - richard - 08-05-2017

You can use session variable to do this, you must be set session on login


RE: Prevent access to pages if session is not set - Wouter60 - 08-05-2017

Try this:
PHP Code:
if (!$this->session->has_userdata('userID')){
 
 redirect('/');