Mini syteme de cache
Posté : 03 mars 2005, 03:24
Voici un mini systeme de cahce tres facilement inégrable dans un site web ou autre , il est basé sur le code d'un ami ( Calimero -> de http://phpsecure.info )
<?php
/*
File: function.cache.php
*/
function cache_exists($path){ // Test si un cache existe ou non pour ce paramètre
return (is_file('cache/'.md5($path).'.txt'));
}
function cache_time($path) {
clearstatcache();
return (filemtime('cache/'.md5($path).'.txt'));
}
function cacheresult ($path, &$data){ // Ecriture du fichier cache pour ce paramètre
_file_put_contents('cache/'.md5($path).'.txt',serialize($data));
}
function &getcache ($path){ // Lecture du fichier cache pour ce paramètre
return unserialize(file_get_contents('cache/'.md5($path).'.txt'));
}
function cache_destroy($path) { // Suppression du cache
unlink('cache/'.md5($path).'.txt');
}
function _file_put_contents($filename, $data, $file_append = false) {
$fp = fopen($filename, (!$file_append ? 'w+' : 'a+'));
if(!$fp) {
trigger_error('file_put_contents cannot write in file.', E_USER_ERROR);
return;
}
fputs($fp, $data);
fclose($fp);
}
?>
et voici un exemple d'utilisation :
<?php
/*
File: accueil.php
*/
$generation = FALSE;
if(cache_exists("top10_irc")) {
$time_cache = time() - cache_time("top10_irc");
if($time_cache > 600) {
cache_destroy("top10_irc");
$generation = TRUE;
}
else {
$top10 = getcache("top10_irc");
}
}
else {
$generation = TRUE;
}
if($generation == TRUE) {
$bot = new BotConnexion() ;
$bot->connect() or die('Connexion Impossible');
$bot->Ident();
$canaux = $bot->chanlistformat();
array_multisort($canaux['users'], SORT_NUMERIC, SORT_DESC,$canaux['name'], SORT_ASC, SORT_STRING, $canaux['topic'], SORT_ASC, SORT_STRING);
$top10 = '';
$top10 .= '<table>';
$top10 .= "<tr><thead><th>Nom</th><th>Users</th></tr></thead><tbody>\n";
for ($i=0;$i<10;$i++) {
$top10 .= '<tr>';
$top10 .= '<td>'.$canaux['name'][$i]."</td>"; // nom
$top10 .= "<td>".$canaux['users'][$i]."</td>"; // users
$top10 .= '</tr>';
}
$top10 .= "</tbody></table>";
cacheresult("top10_irc",$top10);
}
?>