PHP
  Home arrow PHP arrow Page 4 - 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 - Compressing data by "Gzip:" defining the "getCompressedContent()" function
    ( Page 4 of 4 )

    In order to take advantage of the capabilities of PHP for using "Gzip" to compress dynamic pages, what I'll do next is define a simple function which uses the built-in "gzencode()" function to deliver compressed data. The source code that corresponds to this function is listed below:

    (*)function getCompressedContent($data){
      // start output buffer
      ob_start(); 
      // check to see if $data is a file
      if(file_exists($data)){
        // include file into output buffer
        include($data);
      }
      else
      {
        // echo string to output buffer
        echo $data;
      }

      // Get the current buffer and clean it, as well as remove any
      // newline/carrage return from the output
      $data = preg_replace(array("/\r/", "/\n/"), '', ob_get_clean());

      // check if browser supports gzip encoding
      if(strstr($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip')){
        // crunch content & compress data with gzip
        $data=gzencode($data,9);

        // send http header
        header('Content-Encoding: gzip');
      }

      // return data in the proper format
      return $data;
    }

    As you can see, the function defined above shows some significant code changes compared to the procedural script, listed in the previous section. Of course, the first thing worth noting here is the introduction of a checking block, useful for determining whether the browser offers support for "Gzip" encoding. If it does, the incoming data is stored in the output buffer, then gzip-compressed and finally returned to calling code.

    In addition, it's possible to add some "data crunching" capabilities to the above function, by replacing the following line:

    $data=gzencode(ob_get_contents(),9);

    with this one:

    $data=gzencode(preg_replace("/(rn|n)/","",ob_get_contents
    ()),9);

    After the pertinent code modification, the signature for this function would be as follows:

    /*
    // improved function to compress dynamic pages and strings
    // first crunches data and next compresses it by gzip
    */
    function getCompressedContent($data){
        // check if browser supports gzip encoding
        if(strstr($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip')){
            // start output buffer
            ob_start();
            // check to see if $data is a file
            if(file_exists($data)){
                // include file into output buffer
                include($data);
            }
            else{
                // echo string to output buffer
                echo $data;
            }
            // crunch content & compress data with gzip
            $data=gzencode(preg_replace("/
    (rn|n)/","",ob_get_contents()),9);
            // clean up output buffer
            ob_end_clean();
            // send http header
            header('Content-Encoding: gzip');
        }
        // return data
        return $data;
    }

    That's it. Now, the "getCompressedContent()" function is capable of performing a "crunching" process on the input data, as well as compressing it by using "Gzip." On the other hand, in case the browser doesn't support "gzip" encoding, no compression process is applied to the respective data.

    Now that this function has been appropriately defined, the "sample_file.php" file that you saw before can be passed to the function as shown below:

    // display compressed data
    echo getCompressedContent('sample_file.php');

    As you've seen by the sample codes that I wrote, compressing dynamic pages with PHP is not so difficult as it seems, allowing you to significantly accelerate the download time of parsed PHP files. Of course, as with other compression algorithms, benefits will vary, depending on the type and amount of data being compressed, so before using HTTP compression within your PHP scripts, make sure you're getting real advantages.

    To wrap up

    As you know, this tutorial has now concluded. Over this first part of the series, I showed some simple yet effective approaches for compressing dynamic PHP pages, using essentially PHP's built-in "gzencode()" function, along with output buffering control functions.

    In the next article, I'll show you how to use HTTP compression within an object-oriented development environment, reducing the overall download time of your PHP objects. You won't want to miss it!

    * Editor's Note: Thanks to a very helpful reader we have made some changes to the code to correct a small bug.



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

       

    PHP ARTICLES

    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





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