【问题标题】:Codeigniter: headers already sent error [duplicate]Codeigniter:标头已发送错误[重复]
【发布时间】:2011-07-04 04:18:21
【问题描述】:

我有一个具有身份验证控制器和切换用户功能的 CI 应用程序。基本上它所做的一切都是从 URI 中获取一个 ID,从 ID 中获取一些用户数据,分配一些会话数据,然后加载一个视图。

function switch_user(){
    if(!$this->auth_lib->is_admin()){
       $this->session->set_flashdata('status', 'You need to be an administrator to access this page.');
       redirect('auth/login');
    }

    if($id = $this->uri->segment(3)):
            $this->load->model('auth_model', 'auth');
            $username = $this->auth->get_username($id)->account_name;
            $this->session->set_userdata(array('at_id' => $id, 'username' => $username));
            $this->session->set_flashdata('status','User switched.');
    endif;
    $this->load->model('clients_model', 'clients');
    $data['users'] = $this->clients->get_at_clients();
    $this->load->view('auth/switch', $data);
}

我收到以下错误:

Message: Cannot modify header information - headers already sent by (output started at C:\xampp\htdocs\cp\application\controllers\auth.php:130)

第 130 行是 $username = $this->auth->get_username($id)->account_name;

这里是模型函数:

function get_username($at_id){
     $portal = $this->load->database('warehouse', TRUE);
     $portal->select('account_name');
     $portal->where('account_id', $at_id);
     $portal->from('wh_account');

     $query = $portal->get()->result();

     return $query[0];
}

我不明白发生了什么。当我在本地运行代码时,我没有收到错误。但是当我远程运行它时,即通过互联网,我得到了标题错误。

谁能帮忙找出问题所在?

谢谢,

比利

更新

我实际上在 $username = $this->auth->get_username($id)->account_name; 周围放置了一个 var_dump 导致错误的行。我不知道为什么 :(

【问题讨论】:

  • 你能确认你在本地启用了错误报告吗?
  • 你在$query得到结果吗?
  • 是的,它正在返回一个结果。当我在本地运行它时,用户切换成功并且新用户名已正确添加到会话中
  • 我设置了 error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);在切换发生之前在控制器中,我没有收到任何错误

标签: php codeigniter http-headers


【解决方案1】:

我会检查您的任何模型、控制器或库中是否没有关闭 PHP 标记 - 这通常会导致此类错误。

【讨论】:

  • 感谢您的建议,刚刚检查,所有结束标签都在那里:(
  • @iamjonesy - 这就是我的观点,不应该是任何结束标签(这会导致输出空格,从而触发标题)。
  • 嗨 BrynJ 道歉我实际上添加了不正确的代码。我有一个 var_dump 包裹在这一行 $username = $this->auth->get_username($id)->account_name;一旦我删除它,标题错误就停止了。我已将其从代码粘贴中删除,因为我认为它与错误无关。为什么 var_dump 会导致该错误消息?
  • 过早输出/打印数据时会出现这种错误。您可以通过放置“模具”来修复它;在 var_dump 之后。
  • 真的很有帮助!谢谢
【解决方案2】:
  //Your Code is for redirect
    redirect('site/function1');

    //Alternate Code for solve this issue
    $url = 'site/function1';
    echo'
    <script>
    window.location.href = "'.base_url().'index.php?/'.$url.'";
    </script>
    ';

Why I'm getting "cannot modify header information headers already sent by registration_model" error in codeigniter?

【讨论】:

  • 我使用了第二种替代方式,即 javascript,效果很好!比我尝试过的任何事情都重要!谢谢
猜你喜欢
  • 2015-06-17
  • 1970-01-01
  • 2013-05-03
  • 1970-01-01
  • 1970-01-01
  • 2011-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多