Horje
How to create PHP Simple HTML Cache for a Web Page

It will load your page content from html cahced files.


Step-1: Header PHP Code for Cache

Copy and Paste following code very first of your page. Which Page You want to create cache.

header.php
Example: PHP
<?php
$file = ''.$_SERVER['HTTP_HOST'].''.$_SERVER['REQUEST_URI'].'';
$file = str_replace('/', '-', $file);
$cachefile = 'cached/'.$file.'.html';
$cachetime = 18000;

// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
    echo "<!-- Cached copy, generated ".date('H:i', filemtime($cachefile))." -->\n";
    readfile($cachefile);
    exit;
}
ob_start(); // Start the output buffer
?>

Step-2: Footer PHP Code for Cache

Copy and Paste following code very last of your page. Which Page You want to create cache.

footer.php
Example: PHP
<?php
// Cache the contents to a cache file
$cached = fopen($cachefile, 'w');
fwrite($cached, ob_get_contents());
fclose($cached);
ob_end_flush(); // Send the output to the browser
?>

Full Code Example of PHP Simple Cache

Here is full codes.

index.php
Example: PHP
<?php
$file = ''.$_SERVER['HTTP_HOST'].''.$_SERVER['REQUEST_URI'].'';
$file = str_replace('/', '-', $file);
$cachefile = 'cached/'.$file.'.html';
$cachetime = 18000;

// Serve from the cache if it is younger than $cachetime
if (file_exists($cachefile) && time() - $cachetime < filemtime($cachefile)) {
    echo "<!-- Cached copy, generated ".date('H:i', filemtime($cachefile))." -->\n";
    readfile($cachefile);
    exit;
}
ob_start(); // Start the output buffer
?>
HTML Contents
<?php
// Cache the contents to a cache file
$cached = fopen($cachefile, 'w');
fwrite($cached, ob_get_contents());
fclose($cached);
ob_end_flush(); // Send the output to the browser
?>

Output should be:

Full Code Example of PHP Simple Cache





Related Articles
How to create PHP Simple HTML Cache for a Web Page PHP Cache Tutorial
How to minify all code of Your Website PHP Cache Tutorial

Single Articles
Full Code Example of PHP Simple CachePHP Cache Tutorial

Read Full:
PHP Cache Tutorial
Category:
Web Tutorial
Sub Category:
PHP Cache Tutorial
Uploaded by:
Admin
Views:
115