Php Partial Caching

2019-07-17 18:28发布

I want caching some php files partially. for example

<?
echo "<h1>",$anyPerdefinedVarible,"</h1>";
echo "time at linux is: ";
// satrt not been catched section
echo date();
//end of partial cach
echo "<div>goodbye $footerVar</div>";
?>

So cached page should be like as (cached.php)

<h1>This section is fixed today</h1>
<? echo date(); ?>
<div>goodbye please visit todays suggested website</div>

It may be done with templating but I want it directly. Because I want alternative solution.

标签: php caching
1条回答
ら.Afraid
2楼-- · 2019-07-17 19:15

Look at php's ob_start(), it can buffer all output and save this. http://php.net/manual/en/function.ob-start.php

Addition: Look at http://www.php.net/manual/en/function.ob-start.php#106275 for the function you want :) Edit: Here a even simpeler version: http://www.php.net/manual/en/function.ob-start.php#88212 :)


Here some simple, but effective, solution:

template.php

<?php
    echo '<p>Now is: <?php echo date("l, j F Y, H:i:s"); ?> and the weather is <strong><?php echo $weather; ?></strong></p>';
    echo "<p>Template is: " . date("l, j F Y, H:i:s") . "</p>";
    sleep(2); // wait for 2 seconds, as you can tell the difference then :-)
?>

actualpage.php

<?php    
    function get_include_contents($filename) {
        if (is_file($filename)) {
            ob_start();
            include $filename;
            return ob_get_clean();
        }
        return false;
    }

    // Variables
    $weather = "fine";

    // Evaluate the template (do NOT use user input in the template, look at php manual why)
    eval("?>" . get_include_contents("template.php"));
?>

You could save the contents of template.php or actualpage.php with http://php.net/manual/en/function.file-put-contents.php to some file, like cached.php. Then you can let the actualpage.php check the date of cached.php and if too old, let it make a new one or if young enough simply echo actualpage.php or re-evaluate template.php without rebuilding the template.


After comments, here to cache the template:

<?php    
    function get_include_contents($filename) {
        if (is_file($filename)) {
            ob_start();
            include $filename;
            return ob_get_clean();
        }
        return false;
    }

    file_put_contents("cachedir/cache.php", get_include_contents("template.php"));

?>

To run this you can run the cached file directly, or you can include this on an other page. Like:

<?php
    // Variables
    $weather = "fine";

    include("cachedir/cache.php");
?>
查看更多
登录 后发表回答