Welcome Guest, Not a member yet? Register   Sign In
noob question about break function...
#1

[eluser]rich.a.coy[/eluser]
Hello, I'm new to CI and relatively new to PHP. I'm wondering how do you break running a controller?

I have a function to check if someone is logged in at the top of a controller. If they are not logged in I am loading a new view. Problem is the rest of the original controller runs and shows content they should not be seeing without logging in.

Is there a better way to handle the logged in issue? The way I have it now would mean duplicate code on every secured view I think.

I looked in the user guide but I'm not sure what I am looking for. Smile

Thanks for indulging a noob!
#2

[eluser]danmontgomery[/eluser]
The simplest way would be to redirect the user if they are not logged in. You can set a session variable beforehand with the current uri, then redirect back to that page once they are successfully logged in.
#3

[eluser]rich.a.coy[/eluser]
Thanks for replying. I am trying to redirect if they are not logged in, and it is showing the "not logged in view" but it's continuing through the original controller and showing the rest of the protected content.

Here is the code in question:
Code:
class Dashboard extends Controller {
    
    function __construct()
    {
        parent::Controller();
        $this->is_logged_in();
    }
    
    function index()
    {
        $data['main_content'] = 'dashboard';
        $data['body_id'] = 'dashboard';
        $this->load->view('includes/app_template', $data);
    }
    
    function is_logged_in()
    {
        $is_logged_in = $this->session->userdata('is_logged_in');
        
        if(!isset($is_logged_in) || $is_logged_in != true)
        {
            $this->load->view('not_logged_in');
        }
    }
}
#4

[eluser]danmontgomery[/eluser]
You aren't redirecting, you're loading a different view.

Code:
function is_logged_in()
{
  $is_logged_in = $this->session->userdata('is_logged_in');
        
  if(!isset($is_logged_in) || $is_logged_in != true)
  {
    $this->load->helper("url");
    $this->session->set_userdata('redir', current_url());
    redirect("/user/login");
  }
}

Which will set a session variable for the current page, then redirect their browser to the login page (assuming your login page is /user/login). You can then use the 'redir' session variable to redirect them back to the current page when they are logged in.
#5

[eluser]rich.a.coy[/eluser]
Perfect! Thanks.




Theme © iAndrew 2016 - Forum software by © MyBB