Merging CSS Files Into One File / Browser Call

In order to decrease page loading time, it is wise to combine all CSS that is loaded on a page into a single file so that the browser has to only make 1 call to fetch the file, rather than multiple calls to fetch each file (each call requires significant overhead time).

The following script combines all of your CSS files in PHP (on-the-fly) in order to accomplish this feat.


Specify your file names as a comma separated list, ommiting the .css extension for each file. Include the following line of code in your head section of your HTML.

<link rel="stylesheet" type="text/css" href="css.php?strFiles=file1,file2,file3" />


Create a new PHP script named css.php and copy the following code into the file. Adjust the highlighted line to point to where your CSS files are located.

	header( "Content-type: text/css" );

	if( !empty( $_GET["strFiles"] ) ) {
		$arrFiles = explode( ",", $_GET["strFiles"] );
		if( $arrFiles ) {
			foreach( $arrFiles as $strFile ) {
				// Open the CSS file and fetch its contents.
				$objFile = fopen( "css/" . $strFile . ".css", "r" );
				$strContents = fread( $objFile, filesize( $strFile ) );
				fclose( $objFile );
				// Append the contents to the new combined sheet.
				print $strContents;

Leave a Reply

Your email address will not be published. Required fields are marked *