Bundle JavaScript and CSS files with full file paths

I have been looking at the great PHP CSS/JavaScript bundling approach that is presented at rakaz.nl. The suggested approach is great…and works great, but has a small drawback.

The downloaded combine.php must be adjusted and all combined files must exist in the same folder.

Not a big problem, I know, but since I have a structure where css/js files may exist in sub folders, I want to be able to provide the bundle URL with full paths to the files I want to bundle.

Since the original solution is so slick, this is quite easy to achieve. I will not upload my solution for download, since I want you to grab the original code from rakaz.nl so that it receives the visitors it deserves 🙂

Well, let’s get started:

  • In your project root, create a folder called bundle (or whatever you want, it is not that important)
  • In the bundle folder, create an .htaccess file and add the following code:
          RewriteEngine On
          RewriteBase /
          RewriteRule ^css/(.*\.css) /combine.php?type=css&files=$1
          RewriteRule ^javascript/(.*\.js) /combine.php?type=javascript&files=$1
  • In the bundle folder, create a combine.php file and add this content to it.

Well, now you’re practically where the original approach tells you to adjust the PHP code a bit. Instead, do this:

In the combine.php file, replace

          $path = realpath($base . '/' . $element);


          $path = "../" . $element

The code has to be replaced at two places in the PHP file.

That’s it!

The only thing you have to consider now is to use application root relative paths when calling the bundle URL. This will cause your bundle URL to become quiiiite complex, but it works 🙂

For instance, I have my main JavaScript folder in the application root folder content/js. Let’s say that I have the files a.js and b.js (great naming convention, ey?). The bundle URL would then be:


To bundle CSS files, the corresponding code would look like:


Well, you get the point 🙂

The newly added code will add a ../ to each link before attempting to parse the file, which will work great since the combine.php file is placed one level down from the application root…to which the links have to be relative, remember?

The great thing now is that I can bundle any JavaScript/CSS files (they still have to be bundled separately) regardless of their physical location (as long as they exist anywhere within the application root folder).

Another great thing is that the .htaccess file is placed inside the bundle folder, which means that you can just copy the bundle folder if you want to use it in another project.

Hope this helps!