CodeIgniter Forums
set_content_type() Doesn't seem to be working? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Development (https://forum.codeigniter.com/forumdisplay.php?fid=6)
+--- Forum: Issues (https://forum.codeigniter.com/forumdisplay.php?fid=19)
+--- Thread: set_content_type() Doesn't seem to be working? (/showthread.php?tid=62358)



set_content_type() Doesn't seem to be working? - jLinux - 07-05-2015

Hey guys, im trying to set the header type on a page, heres the code, pretty basic:
PHP Code:
public function current()
    {
        
$this->output->set_content_type('text/plain');

        if( ! 
$partition $this->Accounts_model->some_function())
        {
            die(
"No Partition Set");
        }

        echo 
$partition;
    } 

It doesnt at all change the header, however if I change it to this:
PHP Code:
public function current()
    {
        
header("Content-Type:text/plain");

        if( ! 
$partition $this->Accounts_model->some_function())
        {
            die(
"No Partition Set");
        }

        echo 
$partition;
    } 

It works fine. I dug through the Output.php file, and notice on line 467, you disable the errors of the header() function by using a @, if I take that out, I get the error..
Quote:Message: Cannot modify header information - headers already sent by (<MY FILE:LINE>)

Filename: core/Output.php

Line Number: 467

So is there a reason the set_content_type() is executing after the page output?


RE: set_content_type() Doesn't seem to be working? - Avenirer - 07-06-2015

Well... you did the echo $partition inside a controller.... You should use $this->load->view('your_view'); and put that echo inside the view.


RE: set_content_type() Doesn't seem to be working? - CroNiX - 07-06-2015

Yes, you need to use a view, OR use set_output() because of the way CI buffers output. If you echo from a controller, that happens before anything else since the controller has to complete before CI will send IT's data out. And using output->set_content_type() is part of that, which is why it doesn't work the way you wrote it and using native PHP header() does.

A workaround is to finish what you started and send your output using output->set_output()
http://www.codeigniter.com/user_guide/libraries/output.html#CI_Output::set_output

$this->output->set_output($partition); //instead of echo $partition


RE: set_content_type() Doesn't seem to be working? - jLinux - 07-11-2015

Oh, duh, sorry, lol