Bynd
Bynd

Reputation: 705

Yii2 advanced Fatal error Headers already sent in

I'm using Yii2 Advanced. Today without changing anything on my web site that is hosted on a web hosting. I'm getting this message at the bottom of my page on all my web

Fatal error: Uncaught yii\web\HeadersAlreadySentException: Headers
already sent in
    /home/groopakc/public_html/vendor/yiisoft/yii2/web/Response.php on line 414.
    in /home/groopakc/public_html/vendor/yiisoft/yii2/web/Response.php:366
    Stack trace: #0 /home/groopakc/public_html/vendor/yiisoft/yii2/web/Response.php(339): 
    yii\web\Response->sendHeaders() #1 /home/groopakc/public_html/vendor/yiisoft/yii2/web/ErrorHandler.php(135):

    yii\web\Response->send() #2 /home/groopakc/public_html/vendor/yiisoft/yii2/base/ErrorHandler.php(262):

    yii\web\ErrorHandler->renderException(Object(yii\base\ErrorException))
#3 [internal function]: 
    yii\base\ErrorHandler->handleFatalError() #4 {main} 
    thrown in /home/groopakc/public_html/vendor/yiisoft/yii2/web/Response.php on line 366

I'm not using echo in my controllers cause I did read that echo inside controller can cause this error. but I did a checking but I didn't aany echo inside all my controllers

my controller : SiteController.php is

<?php

namespace frontend\controllers;

use Yii;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use frontend\models\Category;
use frontend\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\SignupForm;

/**
 * Site controller
 */

class SiteController extends Controller
{
    /***/
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    /***/
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /***/
    public function actionIndex()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->redirect(['/dashboard']);
        }
        else {
            $categories = $this->findAllCategory();

            return $this->render('/category/viewIndex', [
                'categories' => $categories,
            ]);
        }
    }

    /***/
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->redirect(['/dashboard']);
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {

                return $this->redirect(['/dashboard']);

        } else {

            $model->password = '';

            return $this->renderAjax('/user/usrLog/login', [
                'model' => $model,
            ]);
        }
    }

    /***/
    public function actionSignup()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->redirect(['/dashboard']);
        }

        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                if (Yii::$app->getUser()->login($user)) {
                    return $this->redirect(['/dashboard']);
                }
            }
        }

        return $this->renderAjax('/user/usrLog/signup', [
            'model' => $model,
        ]);
    }

    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        $pswrd = hash('adler32', microtime().time());

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {

            $model->userSavePass($model->userEmail()->email, $pswrd);

            Yii::$app->mailer->compose()
                ->setFrom('[email protected]')
                ->setTo($model->userEmail()->email)
                ->setSubject('New Password Request')
                ->setTextBody('Plain text content')
                ->setHtmlBody('<p>'.$model->userEmail()->username.'</p><p><b>Your request for new password</b></p><p>Your New Password is : '.$pswrd.'</p>')
                ->send();

            return $this->redirect(['index']);  
        }

        return $this->renderAjax('/user/usrLog/requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    /***/
    public function actionLogout()
    {
        if (Yii::$app->user->isGuest || Yii::$app->request->post('value') !== Yii::$app->user->identity->user_pid)
        {
            throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
        }
        elseif ( Yii::$app->request->post('value') == Yii::$app->user->identity->user_pid )
        {
            Yii::$app->user->logout();
            return $this->redirect(['index']);
        }
    }


    protected function findAllCategory()
    {
        return Category::find()->where(['category_statut' => 1])
                ->orderBy(['category_order' => SORT_ASC,])->all();
    }
}

my index.php file

<?php
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

require __DIR__ . '/../../vendor/autoload.php';
require __DIR__ . '/../../vendor/yiisoft/yii2/Yii.php';
require __DIR__ . '/../../common/config/bootstrap.php';
require __DIR__ . '/../config/bootstrap.php';

$config = yii\helpers\ArrayHelper::merge(
    require __DIR__ . '/../../common/config/main.php',
    require __DIR__ . '/../../common/config/main-local.php',
    require __DIR__ . '/../config/main.php',
    require __DIR__ . '/../config/main-local.php'
);

(new yii\web\Application($config))->run();

My Layout file main.php

<?php

/* @var $this \yii\web\View */
/* @var $content string */

use yii\helpers\Html;
use yii\helpers\Url;
use frontend\assets\AppAsset;
use common\widgets\Alert;

use frontend\components\Style\StyleDetectorWidget;
use frontend\components\Style\StyleMediaWidget;
use frontend\components\MainLayout\LayoutHeaderWidget;
use frontend\components\MainLayout\LayoutSidebarWidget;


AppAsset::register($this);

?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
    <meta charset="<?= Yii::$app->charset ?>">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="keywords" content="group,channel,media,share,photo,image,video,gallery,audio,film,social">
    <meta name = "viewport" content ="width=550">
    <link rel="icon" href="<?=Yii::getAlias('@web/gpkicon/favicon.ico')?>">
    <?= Html::csrfMetaTags() ?>
    <title><?= Html::encode($this->title) ?></title>
    <?php $this->head() ?>
    <?= StyleDetectorWidget::widget()?>
    <?= StyleMediaWidget::widget()?>
</head>

<body>
<?php $this->beginBody() ?>

    <!-- Wrapper -->
    <div id="wrapper">
        <div class="lyt-cc-sheet">
            <div class="lyt-cc-table">

                <!-- SIDEBAR -->
                <div id="sdbr" class="lyt-cc-cell lyt-cc-sidebar1">
                    <div id="sdbrSB" class="sbsdbr">
                        <?=LayoutSidebarWidget::widget()?>
                    </div>
                </div>

                <!-- CONTENT -->
                <div class="lyt-cc-cell lyt-cc-content">

                    <div class="header hdr-div" style="background:#eee">
                        <?=LayoutHeaderWidget::widget()?>
                    </div>

                    <div class="row main-row">
                        <?php use pa3py6aka\yii2\ModalAlert; ?>
                        <?= ModalAlert::widget() ?>
                        <?= $content ?>
                    </div>

                </div>

            </div>
        </div>
    </div>

<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>

Upvotes: 1

Views: 10310

Answers (2)

Asyraf Arifin
Asyraf Arifin

Reputation: 3295

Following the advice from Murat Kurbanov, I solved my issue on this by closing the php tag at the end of my file. I just put a ?>

Upvotes: 0

Murat Kurbanov
Murat Kurbanov

Reputation: 837

sometimes such error occurs, when after "?>" you put some chars like as space or new line. You need remove them and save file. It may work on localhost, but not working on real hosting.enter image description here

?>
<-- you need remove new line
<-- you need remove new line

Upvotes: 5

Related Questions