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>

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>

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>

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.

<?php
	if (substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip'))
		ob_start("ob_gzhandler");
	else
		ob_start();
?>

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>

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

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.

<?php

   // 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);
?>

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>

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.

<?php

   // 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);
?>

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>

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 :)


Facebook  Twitter      Stumbleupon  Delicious
  

37 Comments on “Compress PHP, CSS, JavaScript(JS) & Optimize website performance.”

  • Gaurav wrote on 4 February, 2009, 15:49

    Nice picture dude..!!!

  • Eric Wendelin wrote on 4 February, 2009, 21:14

    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.

  • Disaster wrote on 4 February, 2009, 22:51

    Awesome article, thanks! Will come in handy in future projects :)

  • Viral Patel wrote on 5 February, 2009, 9:22

    @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.

  • nightS wrote on 5 February, 2009, 13:21

    Thank you so much!

  • iDevelopThings wrote on 7 February, 2009, 7:14

    Great article…!

  • carson wrote on 14 February, 2009, 17:50

    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?

  • Viral Patel wrote on 18 February, 2009, 14:43

    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.

  • Tejas Mehta wrote on 22 April, 2009, 11:33

    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

  • Deepak G wrote on 9 May, 2009, 15:23

    Thanks Viral,

    It helped me also.

  • Steffen wrote on 8 June, 2009, 3:02

    Thanks for that great article! It really helped me understanding the whole thing!
    But I’m wondering why you’re not caching images? What’s the reason for it, as images normally don’t change?

  • Arafat Rahman wrote on 8 June, 2009, 9:28

    It helps me a lot.

    Thanks

  • Anton Ongsono wrote on 10 June, 2009, 14:00

    Great Post man..

  • Paul wrote on 11 June, 2009, 15:02

    What about if you have multiple javascript calls on the one page? I get errors

    I used the last methods for css and also javascript (ie creating .htaccess entry and php file)

    Error Says:
    <b>Warning</b>: ob_start() [<a href=\'ref.outcontrol\'>ref.outcontrol</a>]: output handler \’ob_gzhandler\’ cannot be used twice in **file name**

    Does anyone have a way of helping me out of this predicament.

    Thanks

  • Balaji wrote on 20 June, 2009, 13:13

    Thanks for the nice post. But I am facing a problem with IE6 accessing gzip contents(css/javascript files). The apache web server sends gzip contents correctly, but the IE6 doesnt seem to pick gzip contents up. I tried HTTP Analyzers to debug further and I could clearly see that the header option “Accept-Encoding” is missing. I dont have any idea how to include this header option through javascript.
    Now I suspect the following.
    1) Any IE6 security updates are restricting compressed contents to be read/parsed?
    2) Any windows firewall options or firewall softwares or antivirus softwares are restricting the compressed contents?
    3) Or is there any other windows softwares that restrict due to security reasons?
    If yes, Could any one of you please give me a list of applications that might impose such a restriction.

    Am using IE6.0.2900.5512.xpsp_sp3_gdr.090206-1234

    Many thanks
    Balaji

  • Abhishek Singh Mandloi wrote on 20 June, 2009, 18:04

    Hi Viral,
    First of all, thanks for the wonderful tutorial.You have made my day. I was tweaking and searching for the whole day on this issue, but now looks like I have got a sulution.

    I am using powweb as my host and they do not support gzip module.

    I tried your \"GZip using php_value directive in htaccess\" but it failed.
    Even on making a new gzip-enable.php and modifying htaccess, I get server internal error.

    I find that your pages are gzipped, which medhod do you use?

    Any help will be highly appreciated.

  • Viral Patel wrote on 20 June, 2009, 19:02

    Hi Abhishek,
    Try to add following entry in your .htaccess file and see if it is working.

    <FilesMatch "\.(txt|html|htm|php)">
    	php_value output_handler ob_gzhandler
    </FilesMatch>
    

    You may want to add css and js in the FileMatch tag to add gzip compression to css and js files.

    Hope this will work.

  • fakhruddn wrote on 30 June, 2009, 11:48

    nice article it helps me a lot
    but i dont know why IE7 does not display any thing it says “Internet Explorer cannot display the webpage” it works fine in firefox but does not displaying model dialog..
    and it work fine in opera and chrome can any body suggest me what i did wrong…

  • Abhishek wrote on 13 July, 2009, 9:54

    Thanks tht was helpful!! :)

  • Arthur wrote on 22 July, 2009, 4:23

    Has anyone else tried this in firebug to check for caching??? It works on JS files but not on the CSS?? What am I doing wrong?

  • hen wrote on 27 July, 2009, 14:29

    ANY OF THESE TIPS Doesnt work in godaddy.com?

    I have tried the compressing of css by doing what you said :)

    i create a gzip-css.php put it in my root and insert

    Then after that i copy pasted

    ForceType application/x-httpd-php

    php_value auto_prepend_file “/the/full/path/of/this/file/gzip-css.php”

    into my .htaccess I edited the path of course

    THE RESULT? error 500? internel server error

    hope you can reply on this one. thanks

  • Green Card wrote on 29 July, 2009, 1:25

    Hi Viral,
    My hosting enviroment register.com does not suport gzip either so I was very happy to read your article. i immediatly tried to implement it but got a http-500 error immediatly.
    I created the file gzip-enable.php and included this in the .htaccess file

    <FilesMatch \"\\.(txt|html|htm|php)\">
    ForceType application/x-httpd-php
    php_value auto_prepend_file /includes/gzip-enable.php
    </FilesMatch>
    Then i refreshed my browser and got the 500 error. All my pages are php pages with css and java scripts. Is there something I am missing here?

  • Viral Patel wrote on 29 July, 2009, 14:17

    @Green Card, @hen
    Try to add following entry in your .htaccess file and see if it is working.

    
    	php_value output_handler ob_gzhandler
    
    
  • Green Card wrote on 29 July, 2009, 18:29

    That worked :-)
    Thanks Viral,

  • managed hosting solutions wrote on 30 July, 2009, 15:56

    Although shared hosting is a less expensive way for businesses to create a Web presence, it is usually not sufficient for Web sites with high traffic. These sites need a dedicated Web server, either provided by a Web hosting service or maintained in-house. With shared hosting, numerous web sites are sharing a single server.

  • haberler wrote on 21 August, 2009, 5:27

    really helpful article i bookmarked this page.Thanks again.

  • cock wrote on 1 September, 2009, 13:16

    thisi is good??????????????????? ya really good

  • Viral Patel wrote on 20 October, 2009, 22:28

    @Green Card, @haberler, @cock
    Thanks for the comments :)

  • Philza wrote on 5 November, 2009, 4:09

    Mmmm, I had the exact same issue – I started to get regular hits/spikes of very high traffic, part of growth I guess but it slowed my website to a crawl for many visitors. I too use wordpress – had tried the plugins and they just weren’t enough. When you’re running a site that is growing ultimately you need to consider a dedicated server in order to continue to grow. My site is also hosted in the US but my visitors are international so I needed to consider latency. Moving to a dedicated server increases your options for web performance optimization enormously (as does the cost…sigh…) my host also included a website accelerator called Aptimize and that has really put my site in another league, its now lightening fast and scales the traffic spikes excellently. It really a positive that your dealing with this issue as it is a sign of success.

  • Jef wrote on 13 November, 2009, 21:01

    Thanks for the post, I will look for some of these hint!

  • anparasu wrote on 8 December, 2009, 16:35

    ForceType application/x-httpd-php
    php_value auto_prepend_file “gzip-css.php”
    php_value output_handler ob_gzhandler

    I have added the above code in the .htaccess file. also created the gzip-css.php file. both files are in the root directory. but after placing this css is not working.
    Any ideas what i have done wrong ?

  • Alwi wrote on 22 December, 2009, 18:57

    Woww … very nice posting, I need this post to performance on my blog, and thank …

  • Kris wrote on 17 January, 2010, 23:12

    Hello Viral
    I have a very serious problem. As per your posts i added the following in htaccess

    php_value output_handler ob_gzhandler

    php_value output_handler ob_gzhandler

    ForceType application/x-httpd-php
    php_value auto_prepend_file “https://Mydomain.com/gzip-js.php”

    Instantly I’m getting internal Server Errors. Pls Pls help. I’m on Hostgator Business Hosting.

  • Anparasu wrote on 22 January, 2010, 17:22

    Hi Kris,

    I too faced the same problem and find out that this method wont work if you have apache module PHPSUEXEC installed to your server.

    http://codylindley.com/misc/74/server-security-issues-phpsuexec-textpattern

    You can find the solution after reading the url above.

  • satefan wrote on 24 January, 2010, 1:39

    Paul>> It was a while ago your wrote that, but maybe someone else will encounter that error. I hHad the same problem. Removed the line
    ob_start (“ob_gzhandler”);
    from the js./css.php files and then it worked fine.

  • trv ajans wrote on 28 January, 2010, 2:59

    very god

  • Krishna | PHP Programmer wrote on 27 February, 2010, 21:16

    It was nice post and I tried to use them. But I noticed error or no effect of compression while implementing on the websites hosted on shared server. So which one works best for shared one?

Write a Comment

Gravatars are small images that can show your personality. You can get your gravatar for free today!

Copyright © 2010 ViralPatel.net. All rights reserved.