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

Compressing data by "Gzip:" defining the "getCompressedContent()" function - 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.

TABLE OF CONTENTS:
  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
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

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
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- 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: