dongzun9958 2012-02-24 13:45
浏览 19
已采纳

如何在没有数据库的情况下每5分钟保存Php变量

On my website there is a php function func1(), which gets some info from other resources. It is very costly to run this function.

I want that when Visitor1 comes to my website then this func1() is executed and the value is stored in $variable1=func1(); in a text file (or something, but not a database).

Then a time interval of 5 min starts and when during this interval Visitor2 visits my website then he gets the value from the text file without calling the function func1().

When Visitor3 comes in 20 min, the function should be used again and store the new value for 5 minutes.

How to make it? A small working example would be nice.

  • 写回答

4条回答 默认 最新

  • duanpiangeng8958 2012-02-24 13:50
    关注

    Store it in a file, and check the file's timestamp with filemtime(). If it's too old, refresh it.

    $maxage = 1200; // 20 minutes...
    // If the file already exists and is older than the max age
    // or doesn't exist yet...
    if (!file_exists("file.txt") || (file_exists("file.txt") && filemtime("file.txt") < (time() - $maxage))) {
      // Write a new value with file_put_contents()
      $value = func1();
      file_put_contents("file.txt", $value);
    }
    else {
      // Otherwise read the value from the file...
      $value = file_get_contents("file.txt");
    }
    

    Note: There are dedicated caching systems out there already, but if you only have this one value to worry about, this is a simple caching method.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?