1

I created an Ajax call to login an user and return layout html. But I always get this error :

Exception: Warning: Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/interpack/app/code/Interpack/Customer/Controller/Account/LoginPost.php:130) in /Applications/MAMP/htdocs/interpack/vendor/magento/framework/Stdlib/Cookie/PhpCookieManager.php on line 125 in /Applications/MAMP/htdocs/interpack/vendor/magento/framework/App/ErrorHandler.php:61 Stack trace: #0 [internal function]: Magento\Framework\App\ErrorHandler->handler(2, 'Cannot modify h...', '/Applications/M...', 125, Array) #1 /Applications/MAMP/htdocs/interpack/vendor/magento/framework/Stdlib/Cookie/PhpCookieManager.php(125): setcookie('X-Magento-Vary', 'b150d31bb10baec...', 0, '/', '', false, true) #2 /Applications/MAMP/htdocs/interpack/vendor/magento/framework/Stdlib/Cookie/PhpCookieManager.php(78): Magento\Framework\Stdlib\Cookie\PhpCookieManager->setCookie('X-Magento-Vary', 'b150d31bb10baec...', Array) #3 /Applications/MAMP/htdocs/interpack/vendor/magento/framework/App/Response/Http.php(85): Magento\Framework\Stdlib\Cookie\PhpCookieManager->setSensitiveCookie('X-Magento-Vary', 'b150d31bb10baec...', Object(Magento\Framework\Stdlib\Cookie\SensitiveCookieMetadata)) #4 /Applications/MAMP/htdocs/interpack/var/generation/Magento/Framework/App/Response/Http/Interceptor.php(37): Magento\Framework\App\Response\Http->sendVary() #5 /Applications/MAMP/htdocs/interpack/vendor/magento/module-page-cache/Model/App/Response/HttpPlugin.php(25): Magento\Framework\App\Response\Http\Interceptor->sendVary() #6 /Applications/MAMP/htdocs/interpack/vendor/magento/framework/Interception/Interceptor.php(123): Magento\PageCache\Model\App\Response\HttpPlugin->beforeSendResponse(Object(Magento\Framework\App\Response\Http\Interceptor))
#7 /Applications/MAMP/htdocs/interpack/var/generation/Magento/Framework/App/Response/Http/Interceptor.php(117): Magento\Framework\App\Response\Http\Interceptor->___callPlugins('sendResponse', Array, Array) #8 /Applications/MAMP/htdocs/interpack/vendor/magento/framework/App/Http.php(185): Magento\Framework\App\Response\Http\Interceptor->sendResponse() #9 /Applications/MAMP/htdocs/interpack/vendor/magento/framework/App/Http.php(156): Magento\Framework\App\Http->handleDeveloperMode(Object(Magento\Framework\App\Bootstrap), Object(Exception)) #10 /Applications/MAMP/htdocs/interpack/vendor/magento/framework/App/Bootstrap.php(263): Magento\Framework\App\Http->catchException(Object(Magento\Framework\App\Bootstrap), Object(Exception)) #11 /Applications/MAMP/htdocs/interpack/index.php(39): Magento\Framework\App\Bootstrap->run(Object(Magento\Framework\App\Http))
#12 {main}

So to did that I override the execute method of the loginPost controller :

public function execute()
    {
        if ($this->session->isLoggedIn() || !$this->formKeyValidator->validate($this->getRequest())) {
            if (!$this->getRequest()->isAjax()) {
                /** @var \Magento\Framework\Controller\Result\Redirect $resultRedirect */
                $resultRedirect = $this->resultRedirectFactory->create();
                $resultRedirect->setPath('*/*/');
                return $resultRedirect;
            }
        }

        $login = null;
        if ($this->getRequest()->isAjax()) {
            $login = $this->getRequest()->getParams();
        } else if ($this->getRequest()->isPost()) {
            $login = $this->getRequest()->getPost('login');
        }
        if (!is_null($login)) {
            if (!empty($login['username']) && !empty($login['password'])) {
                try {
                    $customer = $this->customerAccountManagement->authenticate($login['username'], $login['password']);
                    $this->session->setCustomerDataAsLoggedIn($customer);
                    $this->session->regenerateId();
                    if ($this->getCookieManager()->getCookie('mage-cache-sessid')) {
                        $metadata = $this->getCookieMetadataFactory()->createCookieMetadata();
                        $metadata->setPath('/');
                        $this->getCookieManager()->deleteCookie('mage-cache-sessid', $metadata);
                    }
                    if (!$this->getRequest()->isAjax()) {
                        $redirectUrl = $this->accountRedirect->getRedirectCookie();
                        if (!$this->getScopeConfig()->getValue('customer/startup/redirect_dashboard') && $redirectUrl) {
                            $this->accountRedirect->clearRedirectCookie();
                            $resultRedirect = $this->resultRedirectFactory->create();
                            // URL is checked to be internal in $this->_redirect->success()
                            $resultRedirect->setUrl($this->_redirect->success($redirectUrl));
                            return $resultRedirect;
                        }
                    }
                } catch (EmailNotConfirmedException $e) {
                    $value = $this->customerUrl->getEmailConfirmationUrl($login['username']);
                    $message = __(
                        'This account is not confirmed. <a href="%1">Click here</a> to resend confirmation email.',
                        $value
                    );
                    $this->messageManager->addError($message);
                    $this->session->setUsername($login['username']);
                } catch (UserLockedException $e) {
                    $message = __(
                        'The account is locked. Please wait and try again or contact %1.',
                        $this->getScopeConfig()->getValue('contact/email/recipient_email')
                    );
                    $this->messageManager->addError($message);
                    $this->session->setUsername($login['username']);
                } catch (AuthenticationException $e) {
                    $message = __('Invalid login or password.');
                    $this->messageManager->addError($message);
                    $this->session->setUsername($login['username']);
                } catch (LocalizedException $e) {
                    $message = $e->getMessage();
                    $this->messageManager->addError($message);
                    $this->session->setUsername($login['username']);
                } catch (\Exception $e) {
                    // PA DSS violation: throwing or logging an exception here can disclose customer password
                    $this->messageManager->addError(
                        __('An unspecified error occurred. Please contact us for assistance.')
                    );
                }
            } else {
                $this->messageManager->addError(__('A login and a password are required.'));
            }
        }

        if (!$this->getRequest()->isAjax()) {
            return $this->accountRedirect->getRedirect();
        } else {
            // Load layout in function of the status of the user
            $this->_view->loadLayout();
            $this->_view->getLayout()->initMessages();
            if ($this->customerIsLoggedIn()) {
                echo $this->_view->getLayout()->getBlock('customer.popin.connected')->toHtml();
            } else {
                echo $this->_view->getLayout()->getBlock('customer.popin.disconnected')->toHtml();
            }
        }
    }

if I call this function with this url for example : http://magento.lan/customer/account/loginPost?ajax=1&[email protected]&password=Potato123

I get the correct HTML (the user is logged in, if a go in account page I'm connected as the right user) but I get bellow the error I give you at the top of the post.

Can you help me please ?

1 Answer 1

6

add an exit; just after

echo $this->_view->getLayout()->getBlock('customer.popin.disconnected')->toHtml();

and see if this resolves your issue.

4
  • I solve my problem by returning my block html by JSON ;) But thanks it can be an another solution ;)
    – Kpone
    Mar 3, 2017 at 15:22
  • @Sji Joseph, this indeed works! can you explain why this solves the problem? What would be a permanent solution?
    – Tjitse
    Jul 19, 2017 at 11:54
  • @Siju Joshep: Thank you, It solve my issue. Actually I am trying to display data which comes through json. If user is not login there is no any issue, But once I login then this issue will occurred. I just put exit; after my echo line. And problem solve. But what happen here that really don't understand. Can you please explain. "cannot modify header information - headers already sent by"
    – Ravi Soni
    Oct 17, 2018 at 12:08
  • It is due to vendor/magento/module-page-cache/Model/App/Response/HttpPlugin.php:25 $subject->sendVary(); Magento tries to add the magento vary after header are already sent. I reproduiced the same error with invoice pdf output. Nov 26, 2018 at 14:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.