PHP
  Home arrow PHP arrow Page 4 - Using HTTP Compression in PHP: Make Yo...
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
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: 5 stars5 stars5 stars5 stars5 stars / 27
    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:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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.


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · The first part of the series goes through the practical implementation of HTTP...
       · Excellent information there. There is a small bug in your function...
       · Thank you for posting your feedback and comments, and I'm glad to know the article...
       · Removing all line-breaks will mess text inside TEXTAREA or PRE tags.In other...
       · I don't understand the point of this article. PHP does all of this work for you when...
       · Thank you for your comments. What you say is true about TEXTAREA and PRE tags....
       · Thank you for commenting on this article. With reference to your question, certainly...
       · Thank you for finding the bug and your code fix we really appreciate it. We have...
       · Has anyone developed a fix for this issue yet? I'd like to strip whitespaces from my...
       · This is a response to a message posted on Friday, 16 Jun 2006, with reference to...
     

       

    PHP ARTICLES

    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security
    - Building a Content Management System with Co...
    - Filters and Login Systems for Web Applicatio...
    - Working with the Email Class in Code Igniter





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