Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Sending gzip compressed JS/CSS

I created a style.css.php file with this code:

<?php

  $gzip = (ob_get_length() === false && !ini_get("zlib.output_compression") && ini_get("output_handler") != "ob_gzhandler" && extension_loaded("zlib") && substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip') && !headers_sent());

  if(!$gzip) header('Location: style.css');

  header('Content-type: text/css');
  header('Cache-Control: no-cache');
  header('Expires: Mon, 1 Jan 1901 04:20:00 GMT');

  ob_start('ob_gzhandler');

  include "style.css";
?>

What do you think? Is this a good way to compress js/css files? Is there a better way to do this? I'm doing this for a public app. that can be downloaded by anyone. So there will be people on shared hosts with gzip disabled

like image 329
Alex Avatar asked Nov 15 '10 22:11

Alex


2 Answers

No, not OK. There's a lot of things wrong there. The include, no dying after redirecting, not considering the deflate method, ...

This is very simple to do with PHP, as the zlib output handler automatically detects the appropriate compression to send to the client (if any); all you have to do is enable it:

<?php
if (extension_loaded("zlib") && (ini_get("output_handler") != "ob_gzhandler")) {
    ini_set("zlib.output_compression", 1);
}

readfile('style.css');
like image 184
Artefacto Avatar answered Oct 19 '22 17:10

Artefacto


If you're serving your site using Apache, you can use either mod_gzip or mod_deflate. They are usually available on shared hosts and can be configured in .htaccess files.

Add the following lines to your .htaccess file:

AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript

(ie one per mime-type)

like image 29
Adam Hopkinson Avatar answered Oct 19 '22 17:10

Adam Hopkinson