如何判断何时获取新图像?

How to tell when to fetch new image?

我的服务器上有 350 多张图片的副本,当有人试图查看一张图片时,如果超过 5 分钟,我希望我的服务器检查我从中镜像数据的另一个网站(他们坚持要我镜像而不是热链接)并获得最新的副本。关于如何做到这一点有什么想法吗?

我可以执行一个 cron 脚本并获取所有图像,但是这样做有问题。(我的主机限制我每 15 分钟一次,我将不得不获取很多我的用户可能或可能不会实际查看。)

我认为 PHP 中应该有一种方法可以做到这一点,但我不知道从哪里开始。

您可以在您的项目中申请ajax。 使用 ajax 每 5 分钟调用您的服务器并刷新您的内容。 简而言之; AJAX是后台加载数据显示在网页上,不需要重新加载整个页面。

您可以通过 php 脚本提供图像,该脚本允许您在显示图像之前进行必要的检查。

<img src="/index.php/image-name.jpg">

下面是检查的一个选项

// get the image name from the uri
$image = explode("/", $_SERVER['REQUEST_URI'])[2];
// check if the image exists
if (is_file($image)) {
    // get the file age
    $age = filemtime($image);
    if ($age < time() - (60*5)) { // 5 mins old
        // file too old so check for new one
            // do your check and serve the appropriate image
    }
    else
    {
        // get the image and serve it to the user
        $fp = fopen($image, 'rb');
        // send the right headers
        header("Content-Type: image/jpg");
        header("Content-Length: " . filesize($image));
        // dump the picture and stop the script
        fpassthru($fp);
        exit();
    }
}
else
{
    // handle error
}