How to Compress a PHP File
As a webmaster or website developer, you may notice large files that take many seconds to load for your site visitors. Website developers regularly face this problem. If you are already coding in PHP, then you can decrease the load times by compressing the PHP output file. Though you cannot directly compress the PHP code itself, you can compress the output file that is displayed in the web browser, shaving off many valuable seconds. This is achieved with the Zlib compression package. It is available in PHP 3 and higher versions.
Instructions
-
-
1
Open your terminal on your web server. You will need administrative or root access on your server.
-
2
Use one of these commands, depending on which Apache server version you have installed.
For Apache/1.3.27, type:
./configure --without-mysql --with-apxs=/usr/local/apache/bin/apxs --with-zlib
For Apache/2.0.44, type:
./configure --without-mysql --with-apxs2=/usr/local/apache2/bin/apxs --with-zlib
-
-
3
Type "make && make install" on the terminal and hit Enter on your keyboard. This creates and installs the new PHP configuration.
-
4
Open the PHP.ini file with your text editor. Normally, this file is located in the PHP installation directory.
-
5
Add the following text inside the PHP.ini file:
output_buffering = On
output_handler = ob_gzhandler
zlib.output_compression = Off
If the settings already exists, but are different, then copy-and-paste the new settings in place of the old.
Alternatively, you can use this method instead:
output_buffering = Off
output_handler =
zlib.output_compression = On
Both compression methods are acceptable and the resulting compression is nearly identical.
-
6
Save the PHP.ini file. If necessary, upload it back to the same directory you downloaded it.
-
7
Open a PHP you want to compress.
-
8
Insert this code onto the top line: <?php ob_start("ob_gzhandler"); ?>
-
9
Save your PHP file.
-
10
View the PHP file in your web browser so you can test the compression and load time.
-
1
Tips & Warnings
Download and install the latest version of the Zlib compression package so you have the latest technology available on your server.
Backup your PHP installation and other important webpage files before attempting this process.
The "<?php ob_start("ob_gzhandler"); ?>" code can be automatically inserted into all your PHP files if you make practical use of calling a HEADER.PHP file.
Zlib is only compatible with PHP version 3 or higher.
References
Resources
- Photo Credit Design image by Design from Fotolia.com