Nouveau WRInaute
Alors voila, j'ai écris une classe qui gère le cache avec une utilisation simple :
Ce code est inspiré de l'idée de fandecine ici :
https://www.webrankinfo.com/forum/t/script-mise-en-cache-des-pages-php.28614/
que je remercie au passage. Son code me plaisait beaucoup mais difficile à intégrer sur un gros projet.
Dites moi si ça marche pour vous ...
Code:
$cache= new start_cache();
- le cache démarre lors de l'appel a la classe
- le cache s'arrête lorsque la classe meure : en bas de la page
- Vous devez juste regler le repertoire ou attérit votre cache
Code:var $cache_base='/mon/repertoire/physique/de/cache/'; // base path with / ending
- le délai d'expiration par défaut est de 24h, mais on peut spécifier des délais d'expiration
Code:
$cache= new start_cache("monthly");
Code:array( "hourly" => 3600, "daily" => 3600*24,"weekly" => 3600*24*7, "monthly" => 3600*24*30, "yearly" => 3600*24*365 )
- pour faire un test sans cache en appelant la page avec le paramètre "reload" :
http://mon.site.fr/page.php?reload - on peut vider le cache avec une url:
http://mon.site.fr/page.php?clear_cache=daily ,
à utiliser avec un webcron ... - les logs de cache sont disponibles aussi avec ces paramètres :
Code:var $log_file="log.txt"; // append will be done with $cache_base var $log_activated=false;
Code:
<?PHP
class start_cache {
var $cache_base='/mon/repertoire/physique/de/cache/'; // base path with / ending
var $log_file="log.txt"; // append will be done with $cache_base
var $log_activated=false;
function __construct($planing="daily") {
if (isset($_GET['clear_cache'])) $this->clear_cache($this->escape_string($_GET['clear_cache']));
$schedules = array( "hourly" => 3600, "daily" => 3600*24,"weekly" => 3600*24*7, "monthly" => 3600*24*30, "yearly" => 3600*24*365 ); // list of expiration time
$requested_url=$_SERVER['REQUEST_URI']; //read page addresse
$requested_url=ereg_replace('/','-',$requested_url); // URI 2 filename
if($requested_url=="-") $requested_url="-index.html"; // if url=/ rewrite in index.html
$this->cache_dir=$this->cache_base.$planing;
$this->cache_file=$this->cache_base.$planing."/cache".$requested_url; // build full cache file path
$expire=$schedules[$planing]; // get expiration time
$this->cache_activated=@filemtime($this->cache_file)< (time()- $expire) || isset($_GET['reload']) ; //if not exist or expired or forced
if ($this->cache_activated) {
ob_start(); // start buffering for the page nothing is sent to the browser
$this->logging(" cache started for file ".$this->cache_file, "start");
} else { // file exist
include ($this->cache_file); // on le copie ici
$this->logging($this->cache_file , "read");
die();
}
}
// log event used like this -> argument : Message , [Group]
// write string 18/01/2011 11:45:16 -> MYSQL: SELECT * FROM table
function logging($msg, $group="DEFAULT")
{
if($this->log_activated) {
// upper case
$group=strtoupper ($group);
// prepare message
$msg= str_replace("\n"," ",$msg);
$msg= str_replace("\r"," ",$msg);
// open file
$fd = fopen($this->cache_base.$this->log_file, "a");
// write string 18/01/2011 11:45:16 -> MYSQL: SELECT * FROM table
fwrite($fd, date("d/m/Y H:i:s")." -> ". $group. ": ".$msg . "\n");
// close file
fclose($fd);
}
}
function clear_cache($planing="daily") {
$this->logging("$planing called from ip ".$_SERVER['REMOTE_ADDR'], "clear");
if (is_dir($this->cache_base.$planing)) $this->del_tree($this->cache_base.$planing);
die ($planing." cache cleared !");
}
function del_tree($dir)
{
$current_dir = opendir($dir);
while($entryname = readdir($current_dir)) {
if(is_dir("$dir/$entryname") and ($entryname != "." and $entryname!=".."))
{
del_tree("${dir}/${entryname}");
} elseif($entryname != "." and $entryname!="..") {
unlink("${dir}/${entryname}");
}
}
closedir($current_dir);
rmdir(${dir});
$this->logging("remove dir ${dir}", "clear");
}
// samll function to protect from script attack or SQL injections
function escape_string($uvar){
$uvar=preg_replace("/((\%3C)|<)[^\n]+((\%3E)|>)/","",$uvar); // Prevent script CSS attack
return mysql_escape_string($uvar); // prevent mysql attack
}
function __destruct() {
if ($this->cache_activated) {
$contenuCache = ob_get_contents(); //get buffer
ob_end_flush();// end buffer
if (!is_dir($this->cache_dir)) {
mkdir($this->cache_dir); // create dir if needed
$this->logging($this->cache_dir, "create_dir");
}
$fd = fopen($this->cache_file, "w"); // open cache file and clear it
if ($fd) {
fwrite($fd,$contenuCache); // Write cache file
fclose($fd);
$this->logging(" cache ended for file ".$this->cache_file."(".strlen($contenuCache).")", "stop");
}
}
}
}
$cache= new start_cache("yearly");
?>
Votre page hmtl ici
<?php
echo" et vos codes php qui rament... ";
sleep(4);
?>
et tout ce que vous voulez mettre en cache
Ce code est inspiré de l'idée de fandecine ici :
https://www.webrankinfo.com/forum/t/script-mise-en-cache-des-pages-php.28614/
que je remercie au passage. Son code me plaisait beaucoup mais difficile à intégrer sur un gros projet.
Dites moi si ça marche pour vous ...