3

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?

1
  • For someone reading this: DO NOT USE THE CODE FROM OP! The code does not validate filepaths and someone can download the whole website, including PHP files or any file that the user that is running the web server has access to. Commented Jul 5, 2020 at 16:56

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, I added a file extension check (only go further if it's css or js)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.