Search code examples
apachesymfonyhttp-compression

Using gzip / compression in Symfony 2 without mod_deflate


I am working on two different Symfony 2.8 projects running on different servers. It would like to use compression for faster loading. All resources I found point to mod_deflate. But while the first server does not offer mod_deflate at all, the second server cannot use mod_deflate while FastCGI is enabled.

I only found the information, that one can enable compression within the server (mod_deflate) or "in script". But I did not found any detailed on this "in script" solution.

Is is somehow possible to enable compression in Symfony without using mod_deflate?


Solution

  • You can try to gzip content manually in kernel.response event:

    namespace AppBundle\EventListener;
    
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    use Symfony\Component\HttpKernel\KernelEvents;
    use Symfony\Component\HttpKernel\HttpKernelInterface;
    
    class CompressionListener implements EventSubscriberInterface
    {
        public static function getSubscribedEvents()
        {
            return array(
                KernelEvents::RESPONSE => array(array('onKernelResponse', -256))
            );
        }
    
        public function onKernelResponse($event)
        {
            //return;
    
            if ($event->getRequestType() != HttpKernelInterface::MASTER_REQUEST) {
                return;
            }
    
            $request = $event->getRequest();
            $response = $event->getResponse();
            $encodings = $request->getEncodings();
    
            if (in_array('gzip', $encodings) && function_exists('gzencode')) {
                $content = gzencode($response->getContent());
                $response->setContent($content);
                $response->headers->set('Content-encoding', 'gzip');
            } elseif (in_array('deflate', $encodings) && function_exists('gzdeflate')) {
                $content = gzdeflate($response->getContent());
                $response->setContent($content);
                $response->headers->set('Content-encoding', 'deflate');
            }
        }
    }
    

    And register this listener in config:

    app.listener.compression:
        class: AppBundle\EventListener\CompressionListener
        arguments:
        tags:
            - { name: kernel.event_subscriber }