I think your problem is in the structure you thought for the cache, believe me, I have a structure similar to yours that I use on my clients' websites, what I did to solve was add a suffix when mobile and other when desktop, so avoid loading the back-end cache in different user-agent type
That is, the solution of the suffix serves to differentiate the static for cellular and for Desktop. Of course you can make an approach via Javascript, here I’m just presenting how to solve what you already have.
The other suggestion would be to use media queries and solve everything via CSS, but in this case would have to remodel the HTML too.
It became something like:
global.php
<?php
function is_mobile() {
//Se não tiver user-agent definido retorna false/assume como desktop
if (empty($_SERVER['HTTP_USER_AGENT'])) return false;
//Com regex checa as palavras que possivelmente o usuário esta acessando via celular
return preg_match('#iPhone|Android|webOS#', $_SERVER['HTTP_USER_AGENT']) > 0;
}
//Cache de 3600 segundos/mesmo que 1 hora de cache
$cachelimite = 3600;
//Sufixo para Desktop/padrão
$sufixo = '.desktop.html';
if (is_mobile()) {
//Troca o sufixo se for celular
$sufixo = '.mobile.html';
}
//Define a pasta aonde deve ser salvo os estáticos, você pode ajustar
$cachefolder = 'cachepages/';
//Captura a URL com querystring
$url = $_SERVER['PHP_SELF'];
//Gera o caminho do arquivo
$cachefile = realpath($cachefolder . strlen($url) . '_' . sha1($url) . $sufixo);
//verifica se o cache existe e se expirou o tempo limite
if (is_file($cachefile) && filemtime($cachefile) + $cachelimite > time()) {
readfile($cachefile);
exit;
}
//Inicia a captura do buffer
ob_start();
register_shutdown_function(function () use ($cachefile) {
//gravar o buffer no arquivo estático
file_put_contents($cachefile, ob_get_contents());
});
Note that the sha1
there was only example, just as the md5 the sha1 can also conflict, the idea is only a basic example to understand the logic, you can future adapt this.
Pages receive this:
<?php
require_once 'global.php';
then what solves the problem of loading the cache is this:
$sulfixo = '.desktop.html';
if (is_mobile()) {
$sulfixo = '.mobile.html';
}
Of course I made a simplified regex to detect the user-agent:
return preg_match('#iPhone|Android|webOS#', $_SERVER['HTTP_USER_AGENT']) > 0;
But it is only to illustrate, in case you can improve it or adapt to your need, using the pipe separator |
in regular expression.
Possible duplicate of Load javascript depending on viewport?
– Denis Rudnei de Souza
Did you ever read the answers? There’s what you’re looking for.
– Denis Rudnei de Souza