Merge Your CSS and JavaScript Using PHP

Merge all of your CSS and JS into one file to improve server speed.

Inside the body tags on your pages

<link href="css/css.php?set=<?php echo base64_encode(serialize(array('screen','index','boxes'))); ?>" rel="stylesheet" type="text/css" />
<script language="javascript" type="text/javascript" src="js/js.php?set=<?php echo base64_encode(serialize(array('general','popup','tooltip'))); ?>"></script>

yoursite.com/css/css.php

<?php 
header("Content-type: text/css");
if(isset($_GET['set'])) {
	$files = unserialize(base64_decode($_GET['set']));
	if (!empty($files)) {
		foreach($files as $file) {
			$contents = file_get_contents(dirname(__FILE__).'/'.basename($file).'.css');
			$data[] = $contents;
		}
	}
	echo implode("\n",$data);	
}
?>

yoursite.com/js/js.php

<?php 
if(isset($_GET['set'])) {
	$files = unserialize(base64_decode($_GET['set']));
	if (!empty($files)) {
		foreach($files as $file) {
			$contents = file_get_contents(dirname(__FILE__).'/'.basename($file).'.js');
			$data[] = $contents;
		}
	}
	echo implode("\n",$data);	
}
?>

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

nice artikel, i am using it in all my site...
Keep your good work...

very nice and clean code.

thanks a lot.

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Allowed HTML tags: <a> <b> <i> <strong> <cite> <em> <code> <pre> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <css>, <diff>, <drupal5>, <html>, <javascript>, <php>. The supported tag styles are: <foo>, [foo]. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.