PHPBuilder - Serving pre-compressed (gz) files using PHP and a small Rewr



RSS Twitter
Tips Application Architecture

Serving pre-compressed (gz) files using PHP and a small Rewr

by: Daniel Frechette
|
April 18, 2006

Here is my solution for returning precompressed (.gz) files when available:


==== File .htaccess ====


Options +FollowSymlinks
AddType text/x-component .htc
# Redirect requests for css, htc, js and xsl files to a php script
# that will return precompressed (.gz) files when available.
RewriteEngine On
RewriteRule (.*.css|.*.htc|.*.js|.*.xsl) fetchGz.php?f=$1 [NC]


==== File fetchGz.php ====


<?php
/*
** Written by Daniel Frechette, April 2006
** Return a precompressed (.gz) file if available for file
** extensions css, htc, js and xsl.
*/
error_reporting(0); // Turn off all error reporting
$fileName = $_GET["f"];
$contentType = "";
$extArray = explode(".", $fileName);
if (($last = count($extArray) - 1) != 0) {
   switch ($extArray[$last]) {
      case "css":
         $contentType = "text/css";
         break;
      case "htc":
         $contentType = "text/x-component";
         break;
      case "js":
         $contentType = "text/javascript";
         break;
      case "xsl":
         $contentType = "text/xml";
         break;
   }
}
$gzFileName = $fileName.".gz";
if (eregi("gzip",$_SERVER["HTTP_ACCEPT_ENCODING"]) && file_exists($gzFileName)) {
   header("Content-Type: ".$contentType."; charset=UTF-8");
   header("Content-Encoding: gzip");
   header("Content-Length: ".filesize($gzFileName));
   header("File-Name: ".$gzFileName); // Custom header
   readfile($gzFileName);
}
else {
   header("Content-Type: ".$contentType."; charset=UTF-8");
   header("File-Name: ".$fileName); // Custom header
   readfile($fileName);
}
die;
?>


==== Usage example ====


<?xml version="1.0" ...?>
<!DOCTYPE html ...>
<html ...>
<head>
   <style type="text/css">
      @import url(./styles/foo.css);
   </style>
   <script type="text/javascript" src="./scripts/bar.js"></script>
</head>
<body>
   ...
</body>
</html>


How it works

The rewrite rule automatically forwards requests for files foo.css and bar.js to fetchGz.php. The PHP script will check if gzip versions of the files exist (i.e. foo.css.gz and bar.js.gz). If found, it will return the gz versions. Otherwise, it will return the requested file (uncompressed version).

To check if the process works properly, I added a custom header tag called File-Name to indicate which file was returned by the script..

This process is VERY FAST and serves my web files at lightning speed.

Regards,

Daniel

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:
Daniel Frechette

Comment:



Comment:

(Maximum characters: 1200). You have characters left.