如何在PHP中缓存网页?

use*_*580 12 php caching

如何在php中缓存网页,以便在页面未更新时,查看者应该获得缓存副本?

谢谢你的帮助.PS:我是php的初学者.

mau*_*ris 14

实际上,您可以在结束脚本之前保存页面的输出,然后在脚本的开头加载缓存.

示例代码:

<?php

$cachefile = 'cache/'.basename($_SERVER['PHP_SELF']).'.cache'; // e.g. cache/index.php.cache
$cachetime = 3600; // time to cache in seconds

if(file_exists($cachefile) && time()-$cachetime <= filemtime($cachefile)){
  $c = @file_get_contents($cf);
  echo $c;
  exit;
}else{
  unlink($cachefile);
}

ob_start();

// all the coding goes here

$c = ob_get_contents();
file_put_contents($cachefile);

?>
Run Code Online (Sandbox Code Playgroud)

如果您有很多需要此缓存的页面,您可以这样做:

cachestart.php:

<?php
$cachefile = 'cache/'.basename($_SERVER['PHP_SELF']).'.cache'; // e.g. cache/index.php.cache
$cachetime = 3600; // time to cache in seconds

if(file_exists($cachefile) && time()-$cachetime <= filemtime($cachefile)){
  $c = @file_get_contents($cf);
  echo $c;
  exit;
}else{
  unlink($cachefile);
}

ob_start();
?>
Run Code Online (Sandbox Code Playgroud)

cacheend.php:

<?php

$c = ob_get_contents();
file_put_contents($cachefile);

?>
Run Code Online (Sandbox Code Playgroud)

然后只需添加即可

include('cachestart.php');
Run Code Online (Sandbox Code Playgroud)

在脚本的开头.并添加

include('cacheend.php');
Run Code Online (Sandbox Code Playgroud)

在脚本的最后.记住要有一个名为cache的文件夹,并允许PHP访问它.

还要记住,如果你正在进行整页缓存,你的页面不应该有特定于SESSION的显示(例如显示成员的栏或什么),因为它们也将被缓存.查看特定缓存的框架(变量或页面的一部分).