How to increase web site performance by combining and minifing CSS with PHP

Nitasha BatraOct 04, 2019
How to increase web site performance by combining and minifing CSS with PHP

This is very important phase for improving you website's performance. By merging and minifing css files, you can easily increasing you website speed. In this process, we will minimize HTTP requests of loading css files. For implementation of this feature, you just need to create a php file i.e. css.php on your server and define paths of all stylesheet files inside this file in php script.


File Name : css.php

header('Content-type: text/css');
$filesAry 	= [];  // Array of CSS files path
$filesAry[] = 'first.css';
$filesAry[] = 'second.css';
$result = '';
foreach($filesAry as $k => $v){
	$fileData = file_get_contents($v);
	$res = compress_minify_css($fileData);
	$result .= $res;
echo $result;

function compress_minify_css( $minified_data = '' ) {
	/* Remove all comments */
	$regex = array("`^([\t\s]+)`ism"=>'',"`^\/\*(.+?)\*\/`ism"=>"","`([\n\A;]+)\/\*(.+?)\*\/`ism"=>"$1","`([\n\A;\s]+)//(.+?)[\n\r]`ism"=>"$1\n","`(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+`ism"=>"\n");
	$minified_data = preg_replace(array_keys($regex),$regex,$minified_data);

	/* Remove all spaces, tabs, newlines.*/
	 $minified_data = str_replace( array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $minified_data );

	 return $minified_data;

Now, we have to call this file in your website as given below:

<link href="assets/css.php" rel="stylesheet">

This file will combine & minify all css file which you had included in php script at run time and improve your website performance. This is not only limited to the website speed issue. It also avoid you to minify each and every file manually and upload it to the server.