WP-Mix

A fresh mix of code snippets and tutorials

Combine all CSS files with PHP

Here is a simple PHP script that will combine all CSS files (stylesheets) in a given directory. Delivering one CSS file with your web pages is much faster than delivering multiple files because there are fewer HTTP requests involved.

Edit this snippet as indicated with the path to your CSS directory, and then add this script to a blank PHP file named “css.php” (or whatever you’d like):

<?php // combine all CSS files
	header('Content-type: text/css');
	$path_to_css = '/css'; // edit path to css directory
	function get_files($dir = '.', $sort = 0) {
		$files = scandir($dir, $sort);
		$files = array_diff($files, array('.', '..'));
		return $files;
	}
	$files = get_files($path_to_css, 1);
	foreach($files as $file) {
		include_once($path_to_css . '/' . $file);
	} 
?>

After uploading css.php to the server, you can link to it from within your web pages. So instead of doing this:

<link rel='stylesheet' href='http://example.com/css/custom.css' type='text/css' media='all'>
<link rel='stylesheet' href='http://example.com/css/typography.css' type='text/css' media='all'>
<link rel='stylesheet' href='http://example.com/css/structure.css' type='text/css' media='all'>
<link rel='stylesheet' href='http://example.com/css/pancakes.css' type='text/css' media='all'>
<link rel='stylesheet' href='http://example.com/css/monkeys.css' type='text/css' media='all'>
 .
 .
 .

..you only need this:

<link rel='stylesheet' href='http://example.com/css/css.php' type='text/css' media='all'>

Muuch bettah. Now it’s time for a break :)

★ Pro Tip:

USP ProSAC Pro