views:

75

answers:

1

Hi

so I have a css file, style.css. in the same directory I have the images/ folder. How can I make a script that compresses style.css, but from another folder?

Right now I have this:

<?php
  if(isset($_GET['css'])) $file = array('url' => htmlspecialchars($_GET['css']), 'type' => 'text/css');
  if(isset($_GET['js'])) $file = array('url' => htmlspecialchars($_GET['js']), 'type' => 'application/javascript');
  if(!isset($file)) exit();

  header('Content-type: '.$file['type']);
  header('Cache-Control: max-age='.(60*60*6).', must-revalidate');  

  // whitespace+comment removal, in case gzip is off
  function compress($buffer){
    global $file;
    $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
    $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), ' ', $buffer);
    return $buffer;
  }

  if(extension_loaded('zlib'))
    if(substr_count($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')) ob_start("ob_gzhandler");

  else ob_start("compress");

  include($file['url']);    
  ob_end_flush();
?>

and use it something like this:

<style type="text/css">
 @import "http://mysite.com/lib/c.php?css=../style.css";
</style>

everything is ok except that the path to the images inside the css file don't work anymore. i think it's because (images/bg.jpg) becomes (../images/bg.jpg)

can i fix this without having to move my c.php script in the same directory as the stylesheet?

+3  A: 

If your web server has such feature, you can use URL rewriting to keep things tidy.

An example with mod_rewrite:

RewriteRule ^images/style\.css$ lib/c.php?css=../style.css

Then, you can simply:

@import "http://mysite.com/images/style.css";

I also recommend you give a second look to your script. What happens if I load this URL?

http://mysite.com/lib/c.php?css=.htpasswd
Álvaro G. Vicario
thanks, I added a file extension check (only go further if it's css or js)
Alex