-
-
Save carlo-fontanos/f2ab6afaa71f29595b3f0d95f40ad2b0 to your computer and use it in GitHub Desktop.
Combine and Compress CSS Files on-the-fly using PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Combines multiple CSS files into a single file and compresses it on-the-fly. | |
* Usage: | |
* <link rel="stylesheet" type="text/css" href="/css/styles.css.php" /> - | |
* | |
*/ | |
/* Use https://.. instead of //.. for CDNs or else it will not work */ | |
$css_files = array( | |
'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css', | |
'styles.css', | |
'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css', | |
'font-awesome.min.css' | |
); | |
$buffer = ""; | |
foreach ( $css_files as $file ) { | |
$buffer .= file_get_contents( $file ); | |
} | |
/* Remove comments */ | |
$buffer = preg_replace( '!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer ); | |
/* Remove space after colons */ | |
$buffer = str_replace( ': ', ':', $buffer ); | |
/* Remove whitespace */ | |
$buffer = str_replace( array( "\r\n", "\r", "\n", "\t", ' ', ' ', ' ' ), '', $buffer ); | |
/* Enable GZip encoding. */ | |
ob_start( 'ob_gzhandler' ); | |
/* Enable caching */ | |
header( 'Cache-Control: public' ); | |
/* Expire in one month */ | |
header( 'Expires: ' . gmdate('D, d M Y H:i:s', time() + 2592000) . ' GMT' ); | |
/* Set the correct MIME type, because Apache won't set it for us */ | |
header( 'Content-type: text/css' ); | |
/* Write everything out */ | |
echo $buffer; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment