Magento2 – Headers Already Sent Error in Controller

controllerserrormagento-2.1

I am working through Alan Storm's tutorial about the first steps in setting up a Controller in Magento 2 and came across an odd little error on page load after setting up my route:

Warning: Cannot modify header information – headers already sent by (output started at /Applications/MAMP/htdocs/magento_blog/app/code/{Vendor}/{Module}/Controller/Hello/World.php:26)

where line 26 is the var_dump in the controller file:

class World extends \Magento\Framework\App\Action\Action
{
    protected $pageFactory;

    public function __construct(Context $context, PageFactory $pageFactory)
    {
        $this->pageFactory = $pageFactory;
        return parent::__construct($context);
    }

    public function execute()
    {
        var_dump(__METHOD__);
        $page_object = $this->pageFactory->create();
        return $page_object;
    }
}

So the "fix" is to comment this var_dump out and the file works without errors, but that's not what i'm interested in. This kind of error is very rare in Magento, as the rendering is really out of our hands. As long as the configs are right, the page will render.

The common reason for this is a UTF-8 error or some white space at the beginning of the PHP file, both of which aren't happening from my end, as i'm simply calling a controller and dumping the method name.

I have made sure to clear the cache and generation folders, and when i do and reload the page, the page factory does regenerate just fine. I'm not sure if this is where my error might be coming from, as i'm not too accustom to looking over these files (they are generated right???).

If i comment out the lines:

$page_object = $this->pageFactory->create();
return $page_object;

The var_dump will display on the constructed url of the controller. So, in a sense, the issue is is when the $page_object is outputted.

And ideas what might be causing this?

Best Answer

Remove the return inside your constructor, just call the parent and instead using var_dump prefer to use Magento 2 log system magento.stackexchange.com/questions/92434/

You get headers already sent by message because you are printing something before rendering page.

Related Topic