简单的PHP缓存,超过3个部分


Simple PHP caching with more than 3 parts

在一个简单的PHP缓存(与ob_start和文件),我需要的部分(多于-或等于-每页3)不缓存(.PHP动态内容或。PHP文件上下文用户为基础)。

+-----------------+
| CACHING CONTENT |
|                 |
+-----------------+
|   NO CACHING    |
+-----------------+
| CACHING CONTENT |
+-----------------+
|   NO CACHING    |
+-----------------+
|                 |
| CACHING CONTENT |
+-----------------+

在"无缓存"部分中,我希望包含动态内容。我可以缓存三个cached.html文件(选项1),但我更喜欢每个缓存页面只有一个文件(而不是3个页面,选项2)。

  1. 缓存几个文件(head_tag.html, body_part1.html, body_part2.html, body_part3.html…)和中间动态内容(files.php)。
  2. 缓存到唯一的文件,用一些标签替换为动态内容(和…如何?)
  3. 其他

注意:请不要使用第三方系统解决方案(memcached, APC…)。我需要它从基于php的选项。

您可以为页面的非缓存部分使用占位符,并缓存整个页面。例如,整个缓存页面看起来像:

<html>
... (static content)
#DYNAMIC-CONTENT-NAME#
... (static content)
#SECOND-DYNAMIC-CONTENT-PLACEHOLDER#
... (static content)
</html>

然后在PHP中,您只需获取此缓存页面并将所有占位符替换为动态内容。

// obtain the cached page from storage
$cached_page = get_cached_page();
// generate the HTML for the dynamic content
$dynamic_content = get_dynamic_content();
// replace the placeholders with the actual dynamic content
$page = str_replace('#DYNAMIC-CONTENT-NAME#', $dynamic_content, $cached_page);
// display the resulting page
echo $page;

这样,您就可以为动态内容放置任意数量的命名占位符,然后您只需将它们替换为实际内容。

有两种方法可以直接使用php

头试验证实

$cachetime = 60 * 60 * 24 * 7; // 1 Week
header(‘Expires: ‘.gmdate(‘D, d M Y H:i:s’, time()+$expires).’GMT’);

或者通过在文件系统中缓存完整的文件(包含动态内容的/content)(可用于缓存站点的部分内容)

<?php
  $cachefile = "cache/".$reqfilename.".html"; #change $reqfilename to $_SERVER['PHP_SELF'] if you are using in headers, footers, menus files
  $cachetime = 60 * 60 * 24 * 7; // 1 Week
  // Serve from the cache if it is younger than $cachetime
  if (file_exists($cachefile) && (time() - $cachetime < filemtime($cachefile))) {
     include($cachefile);
     exit;
  }
  ob_start(); // start the output buffer
?>
.. Your usual PHP script and HTML here ...
<?php
   // open the cache file for writing
   $fp = fopen($cachefile, 'w'); 
   // save the contents of output buffer to the file
   fwrite($fp, ob_get_contents());
   // close the file
   fclose($fp); 
   // Send the output to the browser
   ob_end_flush(); 
?>

你也可以做的是缓存用户计算机上的文件通过使用头或更新你的htaccess缓存信息。根据安装在主机服务器上的模块不同,htaccess的实现可能会有所不同。我使用:

# Add Expiration
ExpiresActive On
ExpiresDefault "access plus 1 week"
ExpiresByType text/html "access plus 1 day"
ExpiresByType text/php "access plus 1 day"
ExpiresByType image/gif "access plus 1 week"
ExpiresByType image/jpeg "access plus 1 week"
ExpiresByType image/png "access plus 1 week"
ExpiresByType text/css "access plus 1 week"
ExpiresByType text/javascript "access plus 1 week"
ExpiresByType application/x-javascript "access plus 1 week"
ExpiresByType image/x-icon "access plus 1 week"
ExpiresByType image/ico "access plus 1 week"
ExpiresByType text/xml "access plus 1 day"