java多线程    Java入门    vsftp    ftp    linux配置    centos    FRP教程    HBase    Html5缓存    webp    zabbix    分布式    neo4j图数据库    

如何缓存wordpress

<?php
 
function callback($buffer)
{
  // replace all the apples with oranges
  return (str_replace("yuexiaosheng", "java-er.com", $buffer));
}
//ob_start will out put content to a internal buffer
ob_start("callback");
 
?>
<html>
<body>
<p>my name is yuexiaosheng</p>
</body>
</html>
<?php
//will clean internal buffer
//ob_end_clean();
//will out the internal buffer's content.
ob_end_flush();
 
?>

ob_start() 会回调callback这个方法,对buffer中的内容进行修改。buffer就是浏览器整个缓冲区的内容

这个技术可以使用在缓存动态网站上。当网页动态代码执行完毕,准备输出内容的时候进行内容截获,然后动手脚。

这个文件命名为cache.php 丢在wordpress根目录,新建cache目录 给个777权限 wordpress就实现了全体缓存 月小升这么干的。

然后index.php 顶部引入

 require('cache.php');
 
<?php
define('CACHE_ROOT', dirname(__FILE__).'/cache');
define('CACHE_LIFE', 86400); //缓存文件的生命期,单位秒,86400秒是一天
define('CACHE_SUFFIX','.html'); //缓存文件的扩展名,千万别用 .php .asp .jsp .pl 等等
 
$file_name = md5($_SERVER['REQUEST_URI']).CACHE_SUFFIX; //缓存文件名
 
//缓存目录,根据md5的前两位把缓存文件分散开。避免文件过多。如果有必要,可以用第三四位为名,再加一层目录。
//256个目录每个目录1000个文件的话,就是25万个页面。两层目录的话就是65536*1000=六千五百万。
//不要让单个目录多于1000,以免影响性能。
$cache_dir = CACHE_ROOT.'/'.substr($file_name,0,2);
$cache_file = $cache_dir.'/'.$file_name; //缓存文件存放路径
 
 
 
if($_SERVER['REQUEST_METHOD']=='GET'){ //GET方式请求才缓存,POST之后一般都希望看到最新的结果
 if(file_exists($cache_file) && time() - filemtime($cache_file) < CACHE_LIFE){ //如果缓存文件存在,并且没有过期,就把它读出来。
 	$fp = fopen($cache_file,'rb');
 	fpassthru($fp);
 	fclose($fp);
 	exit();
 }
 elseif(!file_exists($cache_dir)){
 	if(!file_exists(CACHE_ROOT)){
 		mkdir(CACHE_ROOT,0777);
 		chmod(CACHE_ROOT,0777);
 	}
 	mkdir($cache_dir,0777);
 	chmod($cache_dir,0777);
 }
 
 function auto_cache($contents){ //回调函数,当程序结束时自动调用此函数
 	global $cache_file;
 	$fp = fopen($cache_file,'wb');
 	fwrite($fp,$contents);
 	fclose($fp);
 	chmod($cache_file,0777);
	clean_old_cache(); //生成新缓存的同时,自动删除所有的老缓存。以节约空间。
	return $contents;
}
 
function clean_old_cache(){
	chdir(CACHE_ROOT);
	foreach (glob("*/*".CACHE_SUFFIX) as $file){
		if(time()-filemtime($file)>CACHE_LIFE){
			unlink($file);
		}
	}
}
ob_start('auto_cache'); //回调函数 auto_cache
}
else{
 if(file_exists($cache_file)){ //file_exists() 函数检查文件或目录是否存在。
unlink($cache_file); //不是GET的请求就删除缓存文件。
}
}
?>


This entry was posted in PHP and tagged , . Bookmark the permalink.
月小升QQ 2651044202, 技术交流QQ群 178491360
首发地址:月小升博客https://java-er.com/blog/wordpress-cache/
无特殊说明,文章均为月小升原创,欢迎转载,转载请注明本文地址,谢谢
您的评论是我写作的动力.

Leave a Reply

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

*

*