【问题标题】:fopen, get_file_contents, alternative for cache purpose?fopen,get_file_contents,用于缓存目的的替代方案?
【发布时间】:2014-12-23 09:24:18
【问题描述】:

我目前正试图弄清楚如何在我的网站上重建缓存。

我有一个缓存插件,效果很好,但我需要让我的 cron 脚本“模拟”重建缓存的真实请求(它没有这个功能)。

我有一个获取所有 URL 的 while 循环,并且使用 fopen 和 get_file_contents,我能够生成缓存,但它没有所有内容(不能用作缓存)。

所以基本上,我需要使用“实际加载 URL”的函数/方法,但可以用作 cron 脚本。

有人可以帮我吗?我是否需要改为发出 HTTP 请求,等等。我迷路了。

注意:如果我用浏览器打开网站,缓存会生成并且是正确的。

使用 fopen 或 get_file_contents,它会检查站点,但不会生成有效的缓存! :-)

这样的工作可以吗:

    <?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.mywebsite.com/");
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch)
echo $data; // Dont echo, it's a cron script
?>

【问题讨论】:

    标签: php caching fopen


    【解决方案1】:

    您可以在访问页面时使用ob_ 方法进行缓存,而不必抓取它们。一些伪代码(只是 if 条件是伪的):

    $cached_file_path = 'some path for cached file';
    //TODO: would use filemtime($cached_file_path) and time() to determine if file was
    //cached today. could also do it every 3 hours, or whatever
    If file has not been cached today or cachefile does not exist, then
    {
        ob_start(); // starts recording the output in a buffer
        //TODO: do all your database reads and echos
        .....
        $contents = ob_get_contents(); // gets all the output for you to save
        //TODO: save contents to file at $cached_file_path
       ....
       ob_end_flush(); // returns the content to client
       //means we can cache the file and send to client at same time
       //so this doesn't have to be run separately
       exit;
    }
    else
    {
        //cache is current, so just serve the cached file
        include($cached_file_path);
        exit;
    }
    

    【讨论】:

    • 是的,它已经做到了。但是系统速度很慢(prestashop),我不能让访问者在访问时缓存站点(5-10 秒)。我需要以某种方式缓存/重建缓存,就像每个星期天晚上一样。谢谢你的建议。还有其他方法可以“模拟”访问吗?
    • @user3502108,所以你可以给它一个请求参数,让它缓存,然后只有一个 cronjob 用这个参数访问页面,它会缓存。
    • 我不是高级用户,但 fopen 实际上像真正的访问一样“加载站点”(我想),但只需要一个参数来“将其全部缓存”。我试图阅读有关 fopen 的所有文档。嗯..你能指出我正确的方向吗?如果没有“真正的访客”,我的问题是不可能的吗? :-)
    • 请注意:它使用 fopen 缓存站点,但它所服务的缓存仍然像 5-10 秒。就像它根本没有缓存一样。
    • @user3502108,这就是为什么我在读取缓存文件时使用include 而不是fopen。当然,在保存时使用fopenfwrite,但在阅读时不要使用。
    【解决方案2】:

    我尝试了不同的方法..

    好吧,如果它把直接链接放到我的 cron 作业管理器中,它确实会刷新缓存。

    一定有办法让我的脚本模仿这种行为?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-29
      • 2014-11-29
      • 1970-01-01
      • 2020-09-06
      • 1970-01-01
      • 2018-11-04
      • 2012-01-31
      相关资源
      最近更新 更多