Compress PHP, CSS, JavaScript(JS) & Optimize website performance.

Since few days we have been registering heavy traffic spikes on our website. This lead to performance issues. As this site is currently hosted on a shared hosting server, it is very difficult to optimize the performance of the site. We are using WordPress as CMS for this blog, hence we decided to install WP-Super cache plugin for WordPress to improve the performance. This plugin will create static HTML files from your blogs post and other pages and save them on web server. These HTMLs are served to client whenever consecutive requests are made. Hence this greatly improve the performance as it reduce PHP parsing and database connections. Bandwidth control is an important task to be followed when your traffic is increasing. With limited monthly bandwidth hosting, your site may run out of bandwidth and thus result in increase in down time. Hence it is very much advisable to compress your websites response with GZip and then serve it to client. Compressing output can significantly improve your websites performance by reducing the size sometimes upto 80%! So how can you enable GZip compression and compress your websites output? Well there are several ways to achieve this. I have listed out following very useful tricks to enable compression.

GZip compression in Tomcat, JBoss server

You can find a full post explaining this trick here.

GZip using mod_gzip, mod_deflate and htaccess

Apache server supports server level GZip compression with the help of module mod_gzip and mod_deflate. You can use this module and enable GZip compression for your website using htaccess file. First you have to check whether your hosting provider has enabled mod_gzip or mod_deflate module or not? To check this, you can use php_info() function of PHP which prints all the information about server and modules. You can enable compression for text and html by adding following lines in your htaccess file.
# compress all text and html: AddOutputFilterByType DEFLATE text/html text/plain text/xml # Or, compress certain file types by extension: <Files *.html> SetOutputFilter DEFLATE </Files>
Code language: HTML, XML (xml)
You can compress all type of content (image, css, js etc) using mod_deflate. Copy following code in htaccess to do this.
<Location /> SetOutputFilter DEFLATE SetEnvIfNoCase Request_URI \ \.(?:gif|jpe?g|png)$ no-gzip dont-vary SetEnvIfNoCase Request_URI \ \.(?:exe|t?gz|zip|gz2|sit|rar)$ no-gzip dont-vary </Location>
Code language: HTML, XML (xml)
Also, you can add following code in your htaccess file and enable compression using mod_gzip.
<IfModule mod_gzip.c> mod_gzip_on Yes mod_gzip_dechunk Yes mod_gzip_item_include file \.(html?|txt|css|js|php|pl)$ mod_gzip_item_include handler ^cgi-script$ mod_gzip_item_include mime ^text/.* mod_gzip_item_include mime ^application/x-javascript.* mod_gzip_item_exclude mime ^image/.* mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.* </IfModule>
Code language: HTML, XML (xml)
This technique only works if mod_gzip or mod_deflate modules are loaded in Apache. In our case, these modules were not there and our hosting provider refused to load it as we were using a shared hosting. So following can be another way of enabling compression.

GZip using PHP ob_start() method

If your hosting provider does not support mod_gzip module, ob_start() method can be used to enable compression in PHP file. For this you need to copy following line in top of the PHP file. You may want to add this line in start of the header file that gets included in every php.
if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler"); else ob_start();
Code language: PHP (php)
Above code will check whether your browser supports gzip, if yes, then it send ob_gzhandler method as handle to ob_start method which buffers the output. Thus output is compressed using ob_gzhandler. Only problem with this method is that you have to manually edit all PHP files or should have a header.php file that gets included in all files. There are still ways to achieve this without touching your PHP files. Read following trick.

GZip using php_value directive in htaccess

php_value directive can be used to append/prepend any PHP files in the request of change the output handler. First we will see how we can prepend a PHP file and achieve this. Copy the PHP code that we saw in above example in a file called gzip-enable.php. Now copy following lines in your htaccess file. Thus you need not to modify any of your PHP files can can prepend a PHP file with ob_start() method to all the files.
<FilesMatch "\.(txt|html|htm|php)"> ForceType application/x-httpd-php php_value auto_prepend_file /the/full/path/gzip-enable.php </FilesMatch>
Code language: HTML, XML (xml)
But what if you don’t want to prepend a PHP file? Still there is a way to specify default output handler using htaccess. Use following line in your htaccess file to tell your apache to register ob_gzhandler handler function as output handler.
php_value output_handler ob_gzhandler
Code language: HTML, XML (xml)

Compress CSS using htaccess and php_value

CSS Stylesheet files occupy significant size in overall webpage size. It is hence advisable to compress these files before sending them to client. This significantly improve the performance of a webpage. For compressing CSS files, we will first create a PHP file gzip-css.php with following code.
// initialize ob_gzhandler function to send and compress data ob_start ("ob_gzhandler"); // send the requisite header information and character set header ("content-type: text/css; charset: UTF-8"); // check cached credentials and reprocess accordingly header ("cache-control: must-revalidate"); // set variable for duration of cached content $offset = 60 * 60; // set variable specifying format of expiration header $expire = "expires: " . gmdate ("D, d M Y H:i:s", time() + $offset) . " GMT"; // send cache expiration header to the client broswer header ($expire);
Code language: PHP (php)
Now add following lines in your htaccess file to enable compression for CSS files.
<FilesMatch "\.(css)"> ForceType application/x-httpd-php php_value auto_prepend_file "/the/full/path/of/this/file/gzip-css.php" </FilesMatch>
Code language: HTML, XML (xml)
Whenever a http request for .css will come to a server, the type of css will get converted to application/x-httpd-php, thus making them parsed using PHP. Then a file gzip-css.php will be prepend to this request which in turns compress the output using ob_start (“ob_gzhandler”) method.

Compress JavaScript (JS) using htaccess and php_value

Similar to above example for CSS, JavaScript files can also be compressed and sent to client. For this create a PHP file gzip-js.php and copy following code in it.
// initialize ob_gzhandler function to send and compress data ob_start ("ob_gzhandler"); // send the requisite header information and character set header ("content-type: text/javascript; charset: UTF-8"); // check cached credentials and reprocess accordingly header ("cache-control: must-revalidate"); // set variable for duration of cached content $offset = 60 * 60; // set variable specifying format of expiration header $expire = "expires: " . gmdate ("D, d M Y H:i:s", time() + $offset) . " GMT"; // send cache expiration header to the client broswer header ($expire);
Code language: PHP (php)
Also add following lines in your htaccess file.
<FilesMatch "\.(js)"> ForceType application/x-httpd-php php_value auto_prepend_file "/the/full/path/of/this/file/gzip-js.php" </FilesMatch>
Code language: HTML, XML (xml)
Do you know other methods of compressing the output of PHP/JS/CSS files? Let me know, I will try to add them in this tutorial. Happy Compressing :)

View Comments

  • Good stuff! Remember, though, that you are preventing your users from caching your CSS and JS. You should check your ratio of new/returning visitors before considering this.

  • @Gaurav, Thanks for the comment.

    @Eric, I forget to mention it in this tutorial. Thanks for pointing this out. I will update the post.

    @Disaster, You welcome :) You can bookmark this tutorial if you find it useful.

  • It sounds good news to me. But in Joomla 1.5 there seems no effect....
    Is it also worked in Joomla! 1.5 with sef enabled?

  • Hi Carson,
    I have not tried this with Joomla, but I think it will work as these are the normal rules under htaccess file. These rules are applied after Joomla sends the output.

  • Hi Viral,
    Nice tutorial. I would like to know that if there any solution to view this compressed file as normal file ? i have tons of files which are compressed. i need to modify their code for my purpose but due to files are compressed. i am not able to do it. if you know than let me know.

    Thanks

Share
Published by
Viral Patel
Tags: Compression CSS htaccess JavaScript Javascript Compression PHP Website optimization

Recent Posts

  • Java

Java URL Encoder/Decoder Example

Java URL Encoder/Decoder Example - In this tutorial we will see how to URL encode/decode…

4 years ago
  • General

How to Show Multiple Examples in OpenAPI Spec

Show Multiple Examples in OpenAPI - OpenAPI (aka Swagger) Specifications has become a defecto standard…

4 years ago
  • General

How to Run Local WordPress using Docker

Local WordPress using Docker - Running a local WordPress development environment is crucial for testing…

4 years ago
  • Java

Create and Validate JWT Token in Java using JJWT

1. JWT Token Overview JSON Web Token (JWT) is an open standard defines a compact…

4 years ago
  • Spring Boot

Spring Boot GraphQL Subscription Realtime API

GraphQL Subscription provides a great way of building real-time API. In this tutorial we will…

4 years ago
  • Spring Boot

Spring Boot DynamoDB Integration Test using Testcontainers

1. Overview Spring Boot Webflux DynamoDB Integration tests - In this tutorial we will see…

4 years ago