Compress PHP, CSS, JavaScript(JS) & Optimize website performance.
- By Viral Patel on February 4, 2009
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 ![]()
Get our Articles via Email. Enter your email address.
Your article served as part of the basis for my newly created offline (batch) script that creates combined, minified and gzipped JS and CSS files. Files are pre-gzipped so no server overhead for compression every time file is served. More info at http://code.google.com/p/compress/
Nice tutorial.. i’ll try this for my web blog.. thanks
You could also minify them in PHP a different way.
I do it this way:
The user, always gets just the minified version with no checking (or just every week or so)

The developer, sets a cookie by logging in as admin, and therefore a filemtime check is done every call, on all the css / js files.
If they are expired, the minified version gets rebuilt..
With minified version I mean, all the files combined into one file. Saves about 10 requests in my case
I then gzip this file too.
// write minified file
$f = fopen( $outfile , ‘w’ );
if ( $f ) {
fwrite( $f, $output );
fclose( $f );
$path = realpath($outfile);
$cmd = “gzip -9 $path -c > $path.gz”;
shell_exec($cmd);
}
I combine this with an htacces trick, to get the scripts and styles served Gzipped, STATICALLY
AddEncoding x-gzip .gz
ForceType text/javascript
Header set Vary Accept-Encoding
AddEncoding x-gzip .gz
ForceType text/css
Header set Vary Accept-Encoding
RewriteCond %{HTTP_USER_AGENT} !”.*Safari.*”
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}.gz -f
RewriteRule ^(.*)\.js $1.js.gz [L,QSA]
RewriteCond %{HTTP_USER_AGENT} !”.*Safari.*”
RewriteCond %{HTTP:Accept-encoding} gzip
RewriteCond %{REQUEST_FILENAME}.gz -f
RewriteRule ^(.*)\.css $1.css.gz [L,QSA]
This performance difference is another 20-25ms per file, measured on Zend server CE linux, on a core2duo e6300 @ 3ghz.
Oh i forget about the cache part:
foreach($files as $file)
{
$file = $realpath.$file;
if ( is_file($file) && $mtime = filemtime($file))
{
$mtimes[] = $mtime;
} }
$hash = md5(json_encode($mtimes));
if(!$hash_compare = $this->cache->get($hash,false))
{
$has_been_modified = true;
$this->cache->set($hash,Date::YEAR);
}
Nice tutorial. But i think doing a compression on server side is a bit overhead on server load. I prefer to compress files once and then just show the compressed version, the online tool http://www.zbugs.com can help avoid annoying manual compression.
I compress my CSS only once with my own created css compressor:
http://www.igloro.info/en/css_compressor.html
but thanks for tut, anways <3
I am using http://csscompressor.in to compress all of css. Its quick and easy to use online. Just try and see.
nice trik. thankyou brother. i will do this on my website
i have installed a script on my website for compression on run time, it works fine but when i check , is it compressed or not i found it is compressed on http://zingro.com/Check-Compression-of-Website.aspx but on other sites i do not find my website is compressed i do not know which is right.
What a dumbass trick
We all have very good internet connections and save 2KB is not worth enough
I get server error 500… when I try to “Compress CSS using htaccess and php_value”. What could be wrong?
Excellent article, but there’s a slight mistake in some of the “Content-Type” headers. The syntax is:
Content-Type: [MIME]; charset=utf-8
Some of the examples use a colon to determine the value for charset– e.g.: charset:utf-8 — where as it should be an equals sign.
Great article, though — I am definitely going to get this up-and-running on my site.
P.S. My hosts, A Small Orange, have upgraded the server to PHP5. I’ve noticed that this seems to have caused problems with the “php_value” directive. Does anyone know any way around this, without having to edit into the php.ini file? (My site’s a host that uses a shared server.)
Very useful post. I could save good amount of bandwidth using this. Thanks
nice trick. thanks
Awesome article, thanks!
very nice posting, I need this post to performance on my blog.
it Will come in handy in my coming projects.