如何判断何时获取新图像


How to tell when to fetch new image?

我的服务器上有一份350多个图像的副本,当有人试图查看一个图像时,如果它超过5分钟,我希望我的服务器与我镜像数据的另一个网站核实(他们坚持要我镜像而不是热链接),并获得最新的副本。有什么想法吗?

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

我想应该有一种在PHP中实现这一点的方法,但我不知道从哪里开始。

您可以通过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
}

您可以在项目中应用ajax。使用ajax每隔5分钟调用一次服务器并刷新内容。简言之AJAX是在后台加载数据并将其显示在网页上,而无需重新加载整个页面。