You can store the result of the concatenation in a new CSS file and access it during a certain period until the cache expires.
<?php
if (empty($_GET['files']))
die();
// Configurações
$cacheExpirationInSeconds = 60;
$directoryOfCss = 'C:\xampp\htdocs\frederico\css\\';
$cacheFile = $directoryOfCss.'cache-'.str_replace(',', '-', $_GET['files']).'.css';
// Verifica se o arquivo cache existe e se ainda é válido
if (file_exists($cacheFile) && (filemtime($cacheFile) > time() - $cacheExpirationInSeconds)) {
// Lê o arquivo cacheado
$cssContent = file_get_contents($cacheFile);
} else {
// Concatena os arquivos
$cssContent = '';
$files = explode(',', $_GET['files']);
foreach ($files as $oneFile) {
if (file_exists($directoryOfCss.$oneFile.'.css')) {
$cssContent .= file_get_contents($directoryOfCss.$oneFile.'.css');
}
}
// Cria o cache
$cssContent .= '/*Gerado em '.date('d/m/Y H:i:s').'*/';
file_put_contents($cacheFile, $cssContent);
}
header('Content-Type: text/css;X-Content-Type-Options: nosniff;');
echo $cssContent;
One advantage of this approach is that you can delete the cached file via programming or manually and avoid problems with outdated caching in your clients' browser.
Another solution for your case is to cache in memory the result of concatenation through some PHP module. On the site "PHP: The Right Way" there is a more detailed explanation. Below is an example of how you would look using Memcache.
<?php
if (empty($_GET['files']))
die();
$directoryOfCss = 'C:\xampp\htdocs\frederico\css\\';
// Conecta ao Memcache
$memcache = new Memcache;
$memcache->connect('127.0.0.1', 11211);
// Monta um identificador para o cache
$key = str_replace(',', '-', $_GET['files']);
// Busca o cache
$cssContent = $memcache->get($key);
// Se não existir o cache, é retornardo o dado original e esse dado é armazenado em cache para as próximas solicitações
if (!$cssContent) {
// Concatena os arquivos
$cssContent = '';
$files = explode(',', $_GET['files']);
foreach ($files as $oneFile) {
if (file_exists($directoryOfCss.$oneFile.'.css')) {
$cssContent .= file_get_contents($directoryOfCss.$oneFile.'.css');
}
}
// Armazena em cache
$expireInSeconds = 300;
$memcache->set($key, $cssContent, false, $expireInSeconds);
}
// Exibe o resultado
echo $cssContent;
// E caso você queira excluir dinamicamente o cache basta executar
$memcache->delete($key);
In Xampp, at least the version I use, does not contain Memcache by default, you would have to install it for this code to work.
We want answers that contain only links?
– Valdeir Psr
For his case the best answer is to point out the two main caching alternatives for him to verify which one is possible to follow. It is no use to post a code using Memcache and its server does not have it enabled.
– Felipe Torretto
can give a practical example of how to cache in memory?
– Renan Hugo
I updated my reply with an example of code using Memcache.
– Felipe Torretto