Caching HTML output with PHP

2019-01-26 21:29发布

I would like to create a cache for my php pages on my site. I did find too many solutions but what I want is a script which can generate an HTML page from my database ex:

I have a page for categories which grabs all the categories from the DB, so the script should be able to generate an HTML page of the sort: my-categories.html. then if I choose a category I should get a my-x-category.html page and so on and so forth for other categories and sub categories.

I can see that some web sites have got URLs like: wwww.the-web-site.com/the-page-ex.html

even though they are dynamic.

thanks a lot for help

标签: php html caching
8条回答
小情绪 Triste *
2楼-- · 2019-01-26 21:52

In my opinion this is the best solution. I use this for cache JSON file for my Android App. It can be simply use in other PHP files. It's optimize file size from ~1mb to ~163kb (gzip).

enter image description here

Create cache folder in your directory

Then Create cache_start.php file and paste this code

<?php
header("HTTP/1.1 200 OK");
//header("Content-Type: application/json"); 
header("Content-Encoding: gzip");

$cache_filename = basename($_SERVER['PHP_SELF']) . "?" . $_SERVER['QUERY_STRING'];
$cache_filename = "./cache/".md5($cache_filename);
$cache_limit_in_mins = 60 * 60; // It's one hour


if (file_exists($cache_filename))
{
    $secs_in_min = 60;
    $diff_in_secs = (time() - ($secs_in_min * $cache_limit_in_mins)) - filemtime($cache_filename);
    if ( $diff_in_secs < 0 )
    {
        print file_get_contents($cache_filename);
        exit();
    }
}
ob_start("ob_gzhandler");
?>

Create cache_end.php and paste this code

<?php
$content = ob_get_contents();
ob_end_clean();
$file = fopen ( $cache_filename, 'w' );
fwrite ( $file, $content );
fclose ( $file );
echo gzencode($content);
?>

Then create for example index.php (file which you want to cache)

<?php
include "cache_start.php";
echo "Hello Compress Cache World!";
include "cache_end.php";
?>
查看更多
可以哭但决不认输i
3楼-- · 2019-01-26 21:54

You can get URLs like that using URL rewriting. Eg: for apache, see mod_rewrite

http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html

You don't actually need to be creating the files. You could create the files, but its more complicated as you need to decide when to update them if the data changes.

查看更多
登录 后发表回答