5

How to enable gzip compression in Yii2?

I have tried to use the code below 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();
SiZE
  • 2,217
  • 1
  • 13
  • 24
Harris
  • 121
  • 1
  • 5

2 Answers2

7

Not sure if this is the best practice, but I made it work by attaching event handler on 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();
Harris
  • 121
  • 1
  • 5
3

It is better idea, you can use it anywhere(like in a 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();
    }
);
ingenious
  • 764
  • 2
  • 8
  • 24