CSS combining script

Combining CSS and javascript files has many benefits. HTTP Header requests are reduced with clients downloading the one file instead of many files. We are also able to give our CSS and javascript files individual names based on when it was created thus forcing users to download the new file when required. This very website uses a combining script that updates itself when new CSS and javascript changes are made. Below is our script in its current state.

<?php $files = array(); $compressedFiles = array(); $directory = dirname(__FILE__) . '/'; $compressAgain = false; $extension = false; if ($handle = opendir($directory)) { while (false !== ($file = readdir($handle))) { if ($file != '.' && $file != '..' && $file != 'compressor.php') { if (preg_match('/^[0-9]{10,}\.[a-z]+/', $file, $match)) { $compressedFiles[] = $file; $extension = strtolower(end(explode('.', $file))); } else { $files[] = $directory . $file; } } } } natsort($files); if (empty($compressedFiles)) { $compressAgain = true; } else if (!empty($files)) { $time = str_replace('.' . $extension, '', $compressedFiles[0]); $numberOfFiles = substr($time, -1); $time = substr($time, 0, -1); if ($numberOfFiles != count($files)) { $compressAgain = true; } else { foreach ($files as $file) { if ($time < filemtime($file)) { $compressAgain = true; break; } } } } if ($compressAgain === true) { $data = array(); foreach ($files as $file) { $data[] = file_get_contents($file); } $data = implode("\n", $data); if ($extension === false) { $extension = strtolower(end(explode('.', $files[0]))); } $newCompressedFile = time() . count($files) . '.' . $extension; if (file_put_contents($directory . $newCompressedFile, $data)) { if (!empty($compressedFiles)) { foreach ($compressedFiles as $file) { unlink($directory . $file); } } $compressedFile = $newCompressedFile; } } else { $compressedFile = $compressedFiles[0]; }

Feel free to modify and use the above code to combine your files together for easier downloads and better caching.