CodeIgniter: View doesn't load if I use die() function

为君一笑 提交于 2019-12-23 12:17:32

问题


I have the following code. Checks if the user is logged in or not. When the variable $is_logged_in is not set or is False, I load a message view. Unfortunately, at the same time the system loads the restricted content view. So I used die() function, and now only shows a blank page.

What can I do to only load the message view when the user is not logged in? Thanks.

if(!isset($is_logged_in) OR $is_logged_in == FALSE)
{
     $data['main_content'] = 'not_logged_in';

     $data['data'] = '';

     $this->load->view('includes/template',$data);

     die();
}

回答1:


Actually, I've found an answer to mantain the URL and not redirect:

$data['main_content'] = 'unauthorized_access';
$this->load->view('includes/template', $data);

// Force the CI engine to render the content generated until now    
$this->CI =& get_instance(); 
$this->CI->output->_display();

die();



回答2:


Anyway. I used a redirect to the login page, and a flashdata variable

if(!isset($is_logged_in) OR $is_logged_in == FALSE)
   {
       $this->session->set_flashdata('error_msg','You must be logged in to access restricted area');
       redirect('login/');
   }

Thanks




回答3:


I've been messing around with this for a while. If you're using die or exit after trying to load a view, CI shows a blank page.

The solution would be to use return, which stops execution of the current function, and does not execute anything after below that.

A simple example:

public function validate(){
 //validation code

 if(!$valid){
  $this->load->view('error');
  return;
 }

 //This code won't run
}



回答4:


CI is probably using output buffering (see http://www.php.net/manual/en/ref.outcontrol.php). If you want to load a view and kill the script, you will need to flush the buffer. This would normally be done at the very end of the script, but die()ing stops it from getting there.

if(!isset($is_logged_in) OR $is_logged_in == FALSE)
{
    $data['main_content'] = 'not_logged_in';
    $data['data'] = '';
    $this->load->view('includes/template',$data);

    ob_flush();
    die();
}


来源:https://stackoverflow.com/questions/3489086/codeigniter-view-doesnt-load-if-i-use-die-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!