如何添加缓存以防止HTTP错误508?

时间:2019-07-02 06:28:51

标签: php wordpress

我制作了一个插件,使用uinames.com的API加载了30个随机生成的名称和图片。该插件可以正常工作并显示其内容。像这样:

enter image description here

但是每隔几次刷新一次,我就会得到以下信息:

Warning
: file_get_contents(https://uinames.com/api/?amount=30&region=Netherlands&ext): failed to open stream: HTTP request failed! HTTP/1.1 508 Loop Detected in
C:\xampp\htdocs\wordpress\wp-content\themes\twentynineteen\functions.php

现在我应该通过缓存来解决这个问题,我已经关注了几本教程,但是还不太了解

我的代码:

class PHP_Widget_wpse_12345 extends WP_Widget {
    function __construct() {
        $opts = array(
          'description' => 'Display catfish'
        );
        parent::WP_Widget(
          'test',
          'catfish list',
          $opts
        );
    }
    function widget($args,$instance) {
        $persons = json_decode(file_get_contents('https://uinames.com/api/?amount=30&region=Netherlands&ext'));
        $widget_content = "";

        foreach($persons as $person) {
            $widget_content .= $person->name . ' ' . $person->surname . "<br>" . "<br/> <img src='$person->photo'> <br/>";        
    }           

                echo $widget_content;
    }
}

    function register_my_widgets() {
        register_widget('PHP_Widget_wpse_12345');
    }
add_action('widgets_init','register_my_widgets');

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

您可以使用的方法:

set a flag ($reload = true) to test whether or not to get new file
if the cache file exists
   get the date/time of the cache file
   is the time > refresh time limit
   if yes - set the reload flag to true
   if no  - set the reload flag to false
if reload flag = false
   open file and get contents
otherwise
   get info from the external web site
   get the contents 
   save the contents to cache file