How to enable gzip compression in Yii2

How to enable gzip compression in Yii2?

I tried to use below code in web / index.php but it returns empty

$application = new yii\web\Application($config);
$application->on(yii\web\Application::EVENT_BEFORE_REQUEST, function($event){
    ob_start("ob_gzhandler");
});
$application->on(yii\web\Application::EVENT_AFTER_REQUEST, function($event){
    ob_end_flush();
});
$application->run();

      

+3


source to share


2 answers


Not sure if this is best practice but I did it by adding an event handler to yii \ web \ Response



$application = new yii\web\Application($config);
$application->on(yii\web\Application::EVENT_BEFORE_REQUEST, function(yii\base\Event $event){
    $event->sender->response->on(yii\web\Response::EVENT_BEFORE_SEND, function($e){
        ob_start("ob_gzhandler");
    });
    $event->sender->response->on(yii\web\Response::EVENT_AFTER_SEND, function($e){
        ob_end_flush();
    });
});
$application->run();

      

+4


source


Better idea, you can use it anywhere (like in controller or action):



\yii\base\Event::on(
    \yii\web\Response::className(), 
    \yii\web\Response::EVENT_BEFORE_SEND, 
    function ($event) {
        ob_start("ob_gzhandler");
    }
);

\yii\base\Event::on(
    \yii\web\Response::className(), 
    \yii\web\Response::EVENT_AFTER_SEND, 
    function ($event) {
        ob_end_flush();
    }
);

      

+1


source







All Articles