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();
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();
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();
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With