Есть два способа сделать это с прямым php
Подход заголовка
$cachetime = 60 * 60 * 24 * 7; // 1 Week
header(‘Expires: ‘.gmdate(‘D, d M Y H:i:s’, time()+$expires).’GMT’);
Или путем кэширования полного файла (с включением / содержимым из динамического содержимого) в вашей файловой системе (может использоваться для кэширования частей сайта)
<?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"