Home arrow PHP arrow Page 2 - Using HTTP Compression in PHP: Make Your Web Pages Load Faster

The basics of data compression: writing a simple "crunching" PHP script - PHP

Web developers are always looking for ways to reduce the loading time of their pages. This article, the first of three parts, shows you how to make PHP pages load faster by showing you how to compress dynamic PHP pages. Techniques covered include using PHP's built-in “gzencode()” function, along with output buffering control functions.

  1. Using HTTP Compression in PHP: Make Your Web Pages Load Faster
  2. The basics of data compression: writing a simple "crunching" PHP script
  3. Moving one step forward: using real HTTP compression on parsed PHP files
  4. Compressing data by "Gzip:" defining the "getCompressedContent()" function
By: Alejandro Gervasio
Rating: starstarstarstarstar / 32
April 10, 2006

print this article



A good place to start explaining how you can use HTTP compression within your scripts is by first developing a simple example. This one only "crunches" the dynamic output of a PHP file, by removing all the new lines from it after the file has been parsed.

Bearing in mind this concept, please take a look at the definition of the "sample_file.php" file, which displays some database records from a "users" database table:

// include MySQL class file
require_once 'mysqlclass.php';
// connect to MySQL
$db=&new MySQL(array('host'=>'host','user'=>'user','password'=>'password',
// run SQL query
$result=$db->query('SELECT * FROM users');
// display results
    echo $row['id'].$row['name'].$row['email'].'<br />';

As you can see, the above script also uses a few additional MySQL-related classes, thus for the sake of completeness, here's the signature for them, even though they've been shown in previous articles:

class MySQL {
    var $conId; // connection identifier
    var $host; // MySQL host
    var $user; // MySQL username
    var $password; // MySQL password
    var $database; // MySQL database
    // constructor
    function MySQL($options=array()){
        // validate incoming parameters
            foreach($options as $parameter=>$value){
                    trigger_error('Invalid parameter
            // connect to MySQL
        else {
            trigger_error('No connection parameters were
    // connect to MYSQL server and select database
    function connectDB(){
            trigger_error('Error connecting to the
            trigger_error('Error selecting
    // perform query
    function query($query){
            trigger_error('Error performing query
        // return new Result object
        return new Result($this,$this->result); 

class Result {
    var $mysql; // instance of MySQL object
    var $result; // result set
    function Result(&$mysql,$result){
    // fetch row
    function fetchRow(){
        return mysql_fetch_array($this->result,MYSQL_ASSOC);
    // count rows
    function countRows(){
            return false;
        return $rows;
    // count affected rows
    function countAffectedRows(){
            trigger_error('Error counting affected
        return $rows;
    // get ID from last inserted row
    function getInsertID(){
            trigger_error('Error getting ID',E_USER_ERROR);
        return $id;
    // seek row
    function seekRow($row=0){
            trigger_error('Error seeking data',E_USER_ERROR);
    function getQueryResource(){
        return $this->result;

Right, after listing the classes I used on my previous script, now let me show you how to create a simple snippet that removes new line characters from the corresponding output of the above "sample_file.php" file. Here's the script that does precisely that:

// start output buffer
// parse PHP file
// get 'crunched' buffer contents
// close output buffer
// display file contents
echo $contents;

First of all, I'll highlight a few interesting things regarding the above script. Notice how I used some of PHP's built-in output buffering functions, in order to parse the corresponding sample file and store its "crunched" contents in the $contents variable. This method should clearly demonstrate how useful output buffers can be for applying post processing to parsed files (caching (X)HTML output is another handy implementation of output buffering functions).

As you can see, the logic I applied here is very simple. By removing some white space from the output generated by the previous sample file I reduced its size. In this way I implemented a pseudo compression method, which to be honest is still far from real HTTP compression. However, since this is only my first approach to the problem, it's not so bad at all.

Well, you hopefully learned a basic method for reducing the size of dynamic PHP pages, by using the post-processing capabilities of output buffering. Now, it's time to move on and see how to use real HTTP compression within parsed PHP files. Please keep reading.

>>> More PHP Articles          >>> More By Alejandro Gervasio

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: