简体   繁体   中英

How to force a php script to use a cached version of the page?

I have a script that sometimes takes a long time to load because the server is busy. The script is simply a webpage that displays specific information from database tables every few minutes. I would like to display the most recent information most of the time, but when the server is busy, I don't want this script to be a burden on the server, but I'd still like it to display the most recent data it has.

Therefore I would like to do a simple check that's something like this:

$load_on_server = sys_getloadavg()[0];
If(load_on_server > $load_limit) {
  display_cached_version();
} else {
  display_regular_version();
}

But I'm unsure how I would go about displaying a cached version. Any ideas?

Store the page in another file and update it on each request. In PHP code check the load and if it is bigger than the number of your CPU cores, file_get_contents the stored page, if it is not, execute your program normally.

use file_put_contents("cache.html") on every successfull fetch from DB and file_get_contents("cache.html") on every request where load is too high.

Here is a native PHP solution for caching result of your query .

Let's suppose almost the same data returned , caching it inside a file can be a good way to increase reponse time performance . so you can deal it with this example :

<?php

if (filemtime('myCacheFile.txt') < time()-1*3600) {
    // declare database connection details  ==> code

    // create connection to database ==> code

    // error handling if connection to database failed ==> code

    // make the SQL call
    if ($result = $db->query("SELECT * FROM myTable")) {
        $rows = array();

        while($row = $result->fetch_array(MYSQL_ASSOC)) {
            $rows[] = $row;
        }

        // store query result in myCacheFile.txt
        file_put_contents('myCacheFile.txt', serialize(json_encode($rows)));


        echo json_encode($rows);
    }

    else {
        echo 'data could not be extracted from the db.';
    }
}
else {
    $data = unserialize(file_get_contents('myCacheFile.txt'));
    return $data;
}

The period of life to refresh data isone hour , so i'm supposing that data can be changed every hour , a way to refresh data in your cache also .

Hope this help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM