A question that is often asked by new PHP programmers is:
“How do we compress the (HTML) page output?”
First of all, why would anyone want to compress their webpages? There are really two reasons why it is useful:
- The page loads faster, especially for users with slower internet connections
- The site uses less bandwidth, which means that the site, especially if it gets lots of traffic, is cheaper to run
The downside to compressing page output is that it uses more CPU processing power, but the benefits usually outweigh the extra processing that needs to take place server-side.
Techniques for Compressing Page Output
There are several ways to compress page output, which we will discuss below:
First of all, it is possible to activate it for all content (both PHP and non-PHP) served by your Apache web server by changing the configuration of Apache. However, for this post, we will focus on doing it with PHP, as that is the subject of this blog.
If you have access to your php.ini configuration file, the preferred method of compressing all PHP output is to do it by modifying the following configuration settings in that file to have these values:
zlib.output_compression = On
zlib.output_compression_level = 5
In the above code, “zlib.output_compression_level” should be set to a value between 1 and 9, with the higher values giving more compression, but using more server (CPU) resources.
Alternatively, if you don’t have access to the php.ini file on your server, you can put the compression code directly in your PHP scripts. To do that, put the following line at the top of all of your PHP pages that you want compressed:
Either way you use, once you think you have everything in place, you can use one of many compression testing websites in order to verify that your site is indeed sending compressed output to browsers.
Is it worth it to set up page compression? In most cases, yes.
For example, on one site I was recently working on, we were serving up about 2 Million pages/month without compression. We had complaints of the site loading slowly for some users (the pages were large), as well as the bandwidth getting expensive, so I took steps to set up page compression using the (first) php.ini method.
After getting it configured, I saw a noticeable decrease in page loading time, even for me with my fast internet connection, and the bandwidth bill dropped to only around 30% of what it was before. At the same time, the load on the dual Xeon processor didn’t move up noticeably, so in this case, I considered it to be a success.
P.S. I am currently able to accept a limited number of additional clients for my PHP Development services. Interested in discussing the possibility of my handling your project for you? Contact me!