Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP/codeigniter - use of exit()

I have a few pages that require login, so all controllers that link to these pages start with

$this->checkSession();
//...rest of the code

CheckSession should verify the session is still live, otherwise display a message and stop the execution of the rest of the code in the controller:

function checkSession()
{
    if (!$this->session->userdata('is_logged_in'))
    {
        //the session has expired!
        $data['main'] = 'confirmation_message';
        $data['title'] = "Session expired";
        $this->load->vars($data);
        $this->load->view('template');
        exit();
    }
}

. I was expecting these instructions to happen in sequence, but I only get a blank page. How can I make sure exit() gets executed only after all views are loaded?

like image 365
Patrick Avatar asked Apr 11 '10 22:04

Patrick


4 Answers

In this case Pedro is correct. If they are not logged in just redirect them, it's even better if you can use Public/Admin named base controllers to stop you having to do this in each separate protected file.

Generally speaking though, if you use exit() it will stop the Output library for running. If you just want to stop the current controller from executing but allow output of the controller you can use return in exactly the same way.

function checkSession()
{
    return (bool) $this->session->userdata('is_logged_in');
}

Then simply:

if(!$this->checkSession())
{
        //the session has expired!
        $data['main'] = 'confirmation_message';
        $data['title'] = "Session expired";
        $this->load->vars($data);
        $this->load->view('template');
        return;
}

exit() should only ever be used if you really want instant death of your application's execution for debugging, error reporting, etc.

like image 131
Phil Sturgeon Avatar answered Sep 21 '22 23:09

Phil Sturgeon


In this case you should not use exit, what you should do if the session is not valid is redirect your app using example:

redirect('/init/login/','refresh');
like image 30
Pedro Avatar answered Sep 21 '22 23:09

Pedro


I had a similar problem. Where I wanted to stop the user to due to no login. But I wanted to offer a list of links for them not simply redirect them to a login page. I am using CI version 1.7.2 and the $this->_output() $this->display->_output() and $this->output->_display() solutions did not work for me. I was however to get my results using the $this->output->get_output() function.

        $this->load->vars($data);
        $this->load->view('template');
        die($this->output->get_output());
like image 21
Keith Ritter Avatar answered Sep 24 '22 23:09

Keith Ritter


$this->output->_display();
exit(); 

Is the correct answer! Thanks to Sam Sehnert... It's hidden in the comments so thought I'd re-post.

like image 24
evilunix Avatar answered Sep 24 '22 23:09

evilunix