Comprimarea fisierelor CSS cu PHP

Aproape tot continutul unei pagini web se poate comprima pentru a scadea timpul incarcarii paginilor si traficul consumat. Poate parea o diferenta mica intre 40KB initial si 28KB comprimat, dar se aduna.

<?php
ob_start('ob_gzhandler');
ob_start('compress');
header('Content-type:text/css; charset:UTF-8');
header('Cache-Control:must-revalidate');
$offset = 60 * 60;
$expstr = 'Expires: ' . gmdate('D, d M Y H:i:s',time() + $offset) . ' GMT';
header($expstr);
set_time_limit(10);
ini_set('log_errors', 'On');
ini_set('display_errors', 'Off');

function compress($buffer) 
{
	$buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
	$buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer);
	$buffer = str_replace('{ ', '{', $buffer);
	$buffer = str_replace(' }', '}', $buffer);
	$buffer = str_replace('; ', ';', $buffer);
	$buffer = str_replace(', ', ',', $buffer);
	$buffer = str_replace(' {', '{', $buffer);
	$buffer = str_replace('} ', '}', $buffer);
	$buffer = str_replace(': ', ':', $buffer);
	$buffer = str_replace(' ,', ',', $buffer);
	$buffer = str_replace(' ;', ';', $buffer);
	return $buffer;
}

$files = array('reset.css', 'forms.css', 'lightbox.css', 'tables.css', 'style.css');
$css = '';
foreach($files as $file) 
{
	$handle = fopen($file, 'r');
	$newcss = fread($handle, filesize($file));
	$css .= compress($newcss);
	fclose($handle);
}
echo $css;
unset($css);
ob_end_flush();

Foloseste cineva o modalitate mai buna de comprimare a fisierelor CSS?

3 thoughts on “Comprimarea fisierelor CSS cu PHP”

Leave a Reply

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