PHP
  Home arrow PHP arrow Page 2 - Using HTTP Compression in PHP: Make Your Web Pages Load Faster
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Using HTTP Compression in PHP: Make Your Web Pages Load Faster
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 28
    2006-04-10


    Table of Contents:
  • Using HTTP Compression in PHP: Make Your Web Pages Load Faster
  • The basics of data compression: writing a simple "crunching" PHP script
  • Moving one step forward: using real HTTP compression on parsed PHP files
  • Compressing data by "Gzip:" defining the "getCompressedContent()" function

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Using HTTP Compression in PHP: Make Your Web Pages Load Faster - The basics of data compression: writing a simple "crunching" PHP script
    ( Page 2 of 4 )

    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',
    'database'=>'database'));
    // run SQL query
    $result=$db->query('SELECT * FROM users');
    // display results
    while($row=$result->fetch()){
        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
            if(count($options)>0){
                foreach($options as $parameter=>$value){
                    if(empty($value)){
                        trigger_error('Invalid parameter
    '.$parameter,E_USER_ERROR);
                    }
                    $this->{$parameter}=$value;
                }
                // connect to MySQL
                $this->connectDB();
            }
            else {
                trigger_error('No connection parameters were
    provided',E_USER_ERROR);
            }
        }
        // connect to MYSQL server and select database
        function connectDB(){
            if(!$this->conId=mysql_connect($this->host,$this-
    >user,$this->password)){
                trigger_error('Error connecting to the
    server',E_USER_ERROR);
            }
            if(!mysql_select_db($this->database,$this->conId)){
                trigger_error('Error selecting
    database',E_USER_ERROR);
            }
        }
        // perform query
        function query($query){
            if(!$this->result=mysql_query($query,$this->conId)){
                trigger_error('Error performing query
    '.$query,E_USER_ERROR);
            }
            // 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){
            $this->mysql=&$mysql;
            $this->result=$result;
        }
        // fetch row
        function fetchRow(){
            return mysql_fetch_array($this->result,MYSQL_ASSOC);
        }
        // count rows
        function countRows(){
            if(!$rows=mysql_num_rows($this->result)){
                return false;
            }
            return $rows;
        }
        // count affected rows
        function countAffectedRows(){
            if(!$rows=mysql_affected_rows($this->mysql->conId)){
                trigger_error('Error counting affected
    rows',E_USER_ERROR);
            }
            return $rows;
        }
        // get ID from last inserted row
        function getInsertID(){
            if(!$id=mysql_insert_id($this->mysql->conId)){
                trigger_error('Error getting ID',E_USER_ERROR);
            }
            return $id;
        }
        // seek row
        function seekRow($row=0){
            if(!mysql_data_seek($this->result,$row)){
                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:

    $file='sample_file.php';
    // start output buffer
    ob_start();
    // parse PHP file
    include($file);
    // get 'crunched' buffer contents
    $contents=preg_replace("/(rn|n)/","",ob_get_contents());
    // close output buffer
    ob_end_clean();
    // 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
     

       

    PHP ARTICLES

    - Using Directory Iterators to Build Loader Ap...
    - Using the spl_autoload() Functions to Build ...
    - Working Out of the Object Context to Build L...
    - Using the _autoload() Magic Function to Buil...
    - The Destruct Magic Function in PHP 5
    - The Autoload Magic Function in PHP 5
    - Developing a Recursive Loading Class for Loa...
    - The Sleep and Wakeup Magic Functions in PHP 5
    - Using the Clone Magic Function in PHP 5
    - Including Files Recursively with Loader Appl...
    - The Call Magic Function in PHP 5
    - Designing a Captcha System with PHP and MySQL
    - Using Static Methods to Build Loader Apps in...
    - The Isset and Unset Magic Functions in PHP 5
    - Advanced PHP Form Input Validation to Check ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 hosted by Hostway
    Stay green...Green IT